在dart/flutter中如何使用Shared preferences保存和获取一个列表的列表

3
我一直在尝试使用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();,然后再保存它。但是,即使它是一个只包含字符串的列表,异常仍然存在。

尝试: List<String> new_data = data.expand((i) => i).toList(); - Mehmet Esen
@mathronaut 已经尝试过了,它仍然返回相同的异常。 - Srikanth Varma
3
最简单的方法可能是将其转换为JSON格式并保存结果字符串。 - Richard Heap
不应该是 List<List<String>> 吗? - Dani
你好。你解决了这个问题吗?将其转换为JSON并将结果保存为字符串似乎没有帮助。谢谢! - Igor Tupitsyn
显示剩余2条评论
1个回答

3
我们可以使用 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
}

被低估的。这个答案应该被接受。 - sambam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接