将特定类型的列表存储到共享首选项

Store list of a particular type to shared preference

我有我的清单,这是我从 json 获得的。所以,我想通过共享偏好传递该列表。但是,当我尝试使用共享首选项的 setStringList 时,我遇到了异常。

type 'List<ApprovalStatus>' is not a subtype of type 'List<String>'

而ApprovalStatus是一个class,定义为:

class ApprovalStatus {
  final items;
  final index;
  final approvalStatus;

  ApprovalStatus({this.items, this.index, this.approvalStatus});

  @override
  String toString() {
    return "${this.approvalStatus}";
  }
}

我们不能使用用户定义类型列表来共享首选项/如果不能,我们如何使用共享首选项存储用户定义类型列表?

不,您不能直接在共享首选项中存储用户定义的类型。

您可以将它们序列化为字符串格式并存储 那个

您已经知道如何做到这一点,最常见的格式称为 json。

该错误表明您正在尝试直接传递 ApprovalStatus 列表以保存在共享首选项中。它需要一个字符串列表。

试试这个:

prefs.setStringList(approvalList.map((m) => m.toString()).toList());

确保在 toString 中放入一些序列化逻辑,以便您可以取回数据。

或者,您可以直接将 JSON 数组保存为共享首选项中的字符串 属性。