is there way to get a particular data which have been saved using shared preference?


#i Saved all my user data using shared preference to perform autologin and it works well data is saved

 token = responseData['token'];
      userEmail = responseData['user_email'];
      userNicename = responseData['user_nicename'];
      userDisplayName = responseData['user_display_name'];
      userAddress = responseData['user_address'];
      userContact = responseData['user_contact'];
      userId = responseData['user_id'];
      userDisplayUrl = responseData['user_display_url'];
      SharedPreferences prefs = await SharedPreferences.getInstance();
      final userData = jsonEncode({'token':token,'user_email':userEmail,'user_nicename':userNicename,'user_display_name':userDisplayName,'user_address':userAddress,'user_contact':userContact,'user_id':userId,'user_display_url':userDisplayUrl});

#Data is saved in this manner


#now i wanna access single single data like i wanna get that user_id only or user_email only but i dont know how to do it i tried like this

String? userData;

  void initState(){
    // TODO: implement initState
  void getUserId()async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      userData = prefs.getString("userData");

#as i mentioned above all my data is comming in userData but now i wanna fetch my user_id only or user_email but i am unable to


Use jsonDecode to convert it to a Map:

Like so:

setState(() {
  var userId = jsonDecode(prefs.getString("userData"))["user_id"];

To handle the null case:

String? userDataString = prefs.getString("userData");
if(userDataString != null){
  var userId = jsonDecode(userDataString)["user_id"];
  var email = jsonDecode(userDataString)["user_email"];

Answered By – Josteve

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *