I want to print all sharedpreferences content (key,value)
Keys and Values are given by the user
I've tried to put all Keys into a Set using getKeys() Method then loop the Set and retrieve my elements like this:
_favoritePlaces() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
// prefKeys declared as static Set<String>
prefKeys=prefs.getKeys();
if (prefKeys.isNotEmpty) {
for (int i = 0; i < prefKeys.length; i++) {
// this is another function expects to find key given as parameter
_drawerItem(prefKeys.elementAt(i).toString());
// expected output should come below
}
}
}
Expected Output : Key0 => Value0
I'm worried there is no such API exposed (publicly) to get all prefs at once by the shared_preferences plugin.
You need to do that yourself. This worked for me:
class MainPage extends StatelessWidget {
Future<List<Widget>> getAllPrefs() async {
final SharedPreferences prefs = await PrefStore().prefs;
return prefs
.getKeys()
.map<Widget>((key) => ListTile(
title: Text(key),
subtitle: Text(prefs.get(key).toString()),
))
.toList(growable: false);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<Widget>>(
future: getAllPrefs(),
builder: (context, snapshot) {
if (!snapshot.hasData) return Container();
return ListView(
children: snapshot.data,
);
}),
);
}
}