skip to Main Content

I am trying to store user data after logging in using Shared Preferences but my code is giving me this error message:

The argument type 'Map<String, dynamic>' can't be assigned to the parameter type 'String'. 

Here is my code:

class UserPerfs
{
  static Future<void> saveUserPerfs(User userData) async
  {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String userJsonData = jsonDecode(userData.toJson());
    await prefs.setString('currentUser', userJsonData);
  }
}

How can I resolve this?

2

Answers


  1. jsonDecode(userData.toJson()) must be converting data to Map<String, dynamic>. You can convert to jsonString then can store in sharedPrefereces.

    Login or Signup to reply.
  2. you are using decode function which requires a json string
    if you want to store the user object then you have to encode it instead

    static Future<void> saveUserPerfs(User userData) async
    {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String userJsonData = json.encode(userData.toJson());
      await prefs.setString('currentUser', userJsonData);
    }
    

    and for retrieving the data use json.decode

    static Future<User> getUserData() async
    {
      SharedPreferences prefs = await SharedPreferences.getInstance();
       final encodedUser=  prefs.getString('currentUser');
       return User.fromJson(json.decode(encodedUser!));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search