Reputation: 175
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.
Upvotes: 3
Views: 1026
Reputation: 3326
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
}
Upvotes: 3