【问题标题】:Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<UserInterests>' shared preferences in flutter未处理的异常:类型 'List<dynamic>' 不是 Flutter 中类型 'List<UserInterests>' 共享首选项的子类型
【发布时间】:2021-01-08 09:10:17
【问题描述】:

在我的应用程序中,我想在共享首选项中存储对象列表,但是当我从共享首选项中获取该数据时,我得到未处理的异常:

类型 List&lt;dynamic&gt; 不是类型 List&lt;UserInterests&gt; 的子类型

异常,没有得到数据

这是我的代码

static void addInterests(List<UserInterests> interests) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('interstsArray', jsonEncode(interests));
  }

  static Future<List<UserInterests>> getInterests() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    List<UserInterests> interests = jsonDecode(prefs.getString('interstsArray'));
    return interests;
  }

static void logoutUserSF() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove("interstsArray");
  }

第二行jsonDecode的getInterests函数出现错误,请给出一些建议

【问题讨论】:

    标签: android ios flutter sharedpreferences


    【解决方案1】:

    jsonDecode()String 转换为List&lt;dynamic&gt;,它不知道UserInterests 类型。您必须编写一个函数/构造函数来自己转换它,例如:

    UserInterests.fromJson(List<dynamic> json){
      firstMember = json['firstMember'];
      secondMember = json['secondMember'];
    }
    

    然后你可以像这样使用它:

    List<UserInterests> interests = [
      for(var json in jsonDecode(prefs.getString('interstsArray')))
         UserInterests.fromJson(json),
    ];
    

    【讨论】:

    • 在我的 userIntersts 类中,我有工厂 UserInterests.fromJson(Map json) => _$UserInterestsFromJson(json); Map toJson() => _$UserInterestsToJson(this);所以我把那个代码放在这里?
    • 如果你已经生成了一个,然后尝试使用它并在它失败时修复它(因为有时类型不能被生成器正确推断)。或者只是重写它,我猜,你的选择:)
    猜你喜欢
    • 2021-08-15
    • 2023-04-03
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 2021-09-16
    • 2021-04-04
    • 1970-01-01
    • 2022-09-26
    相关资源
    最近更新 更多