Hello I am trying to use SharedPreferences in flutter but this error appears:
NoSuchMethodError: Class 'Future<dynamic>' has no instance method 'setString'.
I/flutter ( 5764): Receiver: Instance of 'Future<dynamic>'
Here is my code:
late SharedPreferences pref;
getPref() async {
if (pref == null) {
pref = await SharedPreferences.getInstance();
} else {
return pref;
}
}
getPref.setString("");
CodePudding user response:
"getPref" is a Future function, you need to await it before using "setString" to it.
You can try something like this:
late SharedPreferences pref;
getPref() async {
pref = await SharedPreferences.getInstance();
}
await getPref();
pref.setString("MY_KEY", "MY_VALUE");
Just by careful with using the "late" keyword, you should check when using "pref" that the value is correct and well set.
CodePudding user response:
I suggest to maybe do it like this:
SharedPreferences? pref;
Future<bool> setString(String key, String value) async {
final p = pref ??= await SharedPreferences.getInstance();
return await p.setString(key, value);
}