1

I'm trying to save a Map<String, List<MyObj>> in sharedPreferences.
I tried to use the classic sharedPreferences package, but I'm having trouble.
If I save a string to sharedPreferences, then when I try to retrieve and use json.decode(...), I get the error Unhandled Exception: FormatException: Unexpected character (at character 2)...
If I try to save it using json.encode(...), I get the error Unhandled Exception: Converting object to an encodable object failed: Instance of 'MyObj'.
What I'm trying to save is like this:

{ExampleString: [Instance of 'MyObj', Instance of 'MyObj'...], ExampleString2: [Instance of 'MyObj', Instance of 'MyObj'...], ...}

How can I solve this?
Is there a package that allows you to save map?

Cobolt
  • 935
  • 2
  • 11
  • 24
lukko
  • 67
  • 1
  • 8

1 Answers1

0

You have a custom object:

class User {
  String name;
  String age;
  String location;

  User();
}

Create toJson and fromJson:

Map<String, dynamic> toJson() => {
  'name': name,
  'age': age,
  'location': location,
};

User.fromJson(Map<String, dynamic> json)
    : name = json['name'],
      age = json['age'],
      location = json['location'];

Then save it like this:

prefs.setString(key, json.encode(value));

Load it like this:

json.decode(prefs.getString(key));
stacktrace2234
  • 1,172
  • 1
  • 12
  • 22
  • perfect, seems it's working, the toJson() method were missing, but now i receive the error Unhandled Exception: type '_InternalLinkedHashMap' is not a subtype of type 'Map>' – lukko Aug 20 '21 at 12:10