简体   繁体   中英

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. 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>'

I have tried converting the 2d list into a list using 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:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM