[英]How to save and get a list of lists using Shared preferences in dart/flutter
I have been trying to save a list of lists using shared preferences in dart.我一直在尝试使用 dart 中的共享首选项保存列表列表。 For example, I have a list
List data = [["dave","21","M"],["steven","22","F"]]
and I am trying to save and load as it is but app keeps throwing Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>'
例如,我有一个列表
List data = [["dave","21","M"],["steven","22","F"]]
我正在尝试按原样保存和加载但应用程序不断抛出Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>'
I have tried converting the 2d list into a list using List new_data = data.expand((i) => i).toList();
我尝试使用
List new_data = data.expand((i) => i).toList();
将二维列表转换为列表List new_data = data.expand((i) => i).toList();
and then saving it.然后保存它。 But still, the exception persists even though it is a list containing only strings.
但是,即使它是一个仅包含字符串的列表,异常仍然存在。
We can use jsonEncode
and jsonDecode()
to get the list out:我们可以使用
jsonEncode
和jsonDecode()
来获取列表:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.