How to save and get a list of lists using Shared preferences in dart/flutter
734
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
}
Author by
Srikanth Varma
Updated on December 11, 2022Comments
-
Srikanth Varma over 1 year
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 throwingUnhandled 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.