Flutter:如何将动态列表保存到共享首选项

Flutter : how save list of dynamic to shared preference

我正在尝试将数据列表保存到共享首选项并阅读这些文章,但不适合我:

Flutter save List with shared preferences

Shared Preferences in Flutter cannot save and read List

我有这个列表:

var list =[
       {
          "id" : 1,
          "name" : "ali"
        },
        {
          "id" : 2,
          "name" : "jhon"
        }
      ];

我试过了:

setList() async {
    Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
    final SharedPreferences prefs = await _prefs;
    prefs.setStringList('list', list);
  }

我收到此错误:The argument type 'List<Map<String, Object>>' can't be assigned to the parameter type 'List<String>'

发生错误是因为您的 listMap<String, Object> 类型而不是 String。要解决此问题,您可以使用 jsonEncode 方法将其转换为 String

Future<void> setList() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  final List<String> jsonList = list.map((item) => jsonEncode(item)).toList();
  prefs.setStringList('list', jsonList);
}

如果您现在想要检索此列表,您必须使用 jsonDecode 将其转换回 Map<String, Object>

List<Map<String, Object>> getList() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  final List<String> jsonList = prefs.getStringList('list')
  final List<Map<String, Object> list = jsonList.map((item) => jsonDecode(item)).toList();
  return list;
}