【问题标题】:How do I save Map<String, List<object>> in sharedPreferences in flutter?如何在颤动中将 Map<String, List<object>> 保存在 sharedPreferences 中?
【发布时间】:2021-10-21 21:29:35
【问题描述】:

我正在尝试在 sharedPreferences 中保存 Map&lt;String, List&lt;MyObj&gt;&gt;
我尝试使用经典的sharedPreferences 包,但遇到了麻烦。
如果我将字符串保存到 sharedPreferences,那么当我尝试检索和使用 json.decode(...) 时, 我收到错误 Unhandled Exception: FormatException: Unexpected character (at character 2)...
如果我尝试使用 json.encode(...) 保存它,我会收到错误 Unhandled Exception: Converting object to an encodable object failed: Instance of 'MyObj'
我要保存的是这样的:

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

我该如何解决这个问题?
有没有可以保存地图的包?

【问题讨论】:

    标签: json flutter sharedpreferences flutter-sharedpreference


    【解决方案1】:

    你有一个自定义对象:

    class User {
      String name;
      String age;
      String location;
    
      User();
    }
    

    创建 toJson 和 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'];
    

    然后这样保存:

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

    像这样加载它:

    json.decode(prefs.getString(key));
    

    【讨论】:

    • 完美,似乎它正在工作,toJson() 方法丢失了,但现在我收到错误 Unhandled Exception: type '_InternalLinkedHashMap' is not a subtype of type 'Map>'
    猜你喜欢
    • 1970-01-01
    • 2021-09-14
    • 2015-03-22
    • 2020-10-20
    • 1970-01-01
    • 2018-09-22
    • 2020-08-02
    • 1970-01-01
    • 2018-11-23
    相关资源
    最近更新 更多