【问题标题】:How to save and get a list of lists using Shared preferences in dart/flutter如何使用 dart/flutter 中的共享首选项保存和获取列表列表
【发布时间】:2019-10-05 11:51:54
【问题描述】:

我一直在尝试使用 dart 中的共享首选项保存列表列表。例如,我有一个列表List data = [["dave","21","M"],["steven","22","F"]],我正在尝试按原样保存和加载,但应用程序不断抛出Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>'

我尝试使用List new_data = data.expand((i) => i).toList(); 将二维列表转换为列表,然后保存。但是,即使它是一个仅包含字符串的列表,异常仍然存在。

【问题讨论】:

  • 尝试:列表 new_data = data.expand((i) => i).toList();
  • @mathronaut 已经尝试过了,它仍然返回相同的异常。
  • 好的,我正在创建一个演示。
  • 可能最容易将其转换为 json 并保存生成的字符串
  • @Sukumarvarma 试试 Richard Heap 的解决方案,这就是我要建议你的解决方案。

标签: android list dart flutter


【解决方案1】:

我们可以使用jsonEncodejsonDecode() 来获取列表:

import 'package:shared_preferences/shared_preferences.dart';

List data = [["dave","21","M"],["steven","22","F"]];

handleData() async {
  var prefs = await SharedPreferences.getInstance();
  prefs.setString('key', jsonEncode(data)); // Encode the list here
  print(jsonDecode(prefs.getString('key'))); // Decode then print it out
}

【讨论】:

  • 被低估了。这个答案应该被接受。
猜你喜欢
  • 2023-03-22
  • 2021-08-16
  • 2021-10-02
  • 1970-01-01
  • 2022-01-15
  • 2020-10-31
  • 1970-01-01
  • 1970-01-01
  • 2020-08-12
相关资源
最近更新 更多