Shared Preferences misplugin - flutter

i do same exactly as youtube says but in the end i got this error, do you know what is the problem ?
im using flutter 2.8.1 shared_preferences: ^2.0.13
this is the code
class _AppHomeState extends State<AppHome> {
final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future loadData() async {
final SharedPreferences prefs = await _prefs;
var stringSet = await prefs.getString('sets');
List setList = jsonDecode(stringSet!);
for (var sets in setList) {
c.setList.add(SetModel().fromJson(sets));
}
}
Future saveData() async {
final SharedPreferences prefs = await _prefs;
List items = c.setList.map((e) => e.toJson()).toList();
prefs.setString('sets', jsonEncode(items));
}

try running
flutter clean
see issue here

Modify line number 31 as below:
final SharedPreferences _prefs = SharedPreferences.getInstance();
This will fix your problem.

Related

How can I make this work? My shared preferences seem to store the wrong value?

I have these functions to set, remove etc variables I want globally available. I fear it might be just a small mistake on my behalf. What can I do to fix this?
static setUserId(userId, value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('userId', value);
}
static getUserId() async {
final prefs = await SharedPreferences.getInstance();
prefs.getInt('userId') ?? 0;
}
static removeUserId() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove('userId');
}
static removeAllPreferences() async {
final prefs = await SharedPreferences.getInstance();
await prefs.clear();
}
}
var userId = user.id;
var value = userId?.toInt();
AccountPreferences.setUserId('userId', value);
var companyId = user.role![0].companyId;
var test = AccountPreferences.getUserId();
print(test); ```
When I run the code above all I print out is an instance of Future<dynamic>?
What am I doing wrong?
You should also await when getting the value and for that, you should declare the function getUserId() as Future and also return the function value like this:
static Future<int> getUserId() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getInt('userId') ?? 0;
}
var test = await AccountPreferences.getUserId(); // await inside here too, where you call it

How to retrieve data from Future object properly?

I'm using shared preferences. I want to get the list of strings, but for some reason it's always a null though it shouldn't be. I think I'm making a mistake in asynchronous stuff. Can somebody help me? With explanation if possible.
List<String> getSaved() {
List<String>? items;
Future<SharedPreferences> prefs = SharedPreferences.getInstance();
prefs.then((prefs) async {
items = prefs.getStringList('saved');
});
// SharedPreferences prefs = await SharedPreferences.getInstance();
// items = prefs.getStringList('saved');
return items ?? [];
}
Because you want the result when the future completed your function should be of type Future<List<String>> and you can use then or await knowing that items should be of the same type too
Future<List<String>> getSaved() async {
List<String>? items;
SharedPreferences prefs = await SharedPreferences.getInstance();
items = prefs.getStringList('saved');
// SharedPreferences prefs = await SharedPreferences.getInstance();
// items = prefs.getStringList('saved');
return items ?? [];
}

Flutter : How to use SharedPreference to get List<String>?

I've create an initState in my page and call callData to get favId (type : List) every I open this page. But, when the application start, my compiler show this error message :
_TypeError (type 'List<String>' is not a subtype of type 'String')
and this is my getData's function :
getData(favId) async {
SharedPreferences pref = await SharedPreferences.getInstance();
return pref.getStringList(favId);
}
also this is my saveData's function :
void saveData() async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setStringList("id", favId);
}
How to fix this problem and I can call getData every I open this page in my application?
Thank you :)
if you want to save and retrieve List to and from SharedPreferences, you to use same key to save and retrieve the value.
here is a simple example,
const favKey = 'favoriteKey';
To save data,
void saveData(String favKey, List<String> favorites) async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setStringList(favKey,favorites);
}
To retrive data,
getData(String favKey) async {
SharedPreferences pref = await SharedPreferences.getInstance();
return pref.getStringList(favKey);
}
Note: You need to use same key to set and get data using SharedPreference.
"id" is a String, you need to store a List<String> into setStringList
There are the steps if you want to add an item to the list:
List<String> ids = await getData(favId);
ids.add("id");
saveData(ids, favId);
then change the saveData() to
void saveData(ids, favId) async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setStringList(ids, favId);
}
getData()
List<String> getData(favId) async {
SharedPreferences pref = await SharedPreferences.getInstance();
return pref.getStringList(favId);
}

Shared preferences in flutter - error after flutter clear

i try to use shared preferences in flutter but i get this error and i tried to run flutter clear and still getting the same error
the error
ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
Have you add the SharedPreferences dependecies in pubspec.yaml.If not here's how you do it:
dependencies:
flutter:
sdk: flutter
shared_preferences: ^0.5.8
From the error message I believe SharedPreferences don't have getAll method. Here's some example how you read data from SharedPreferences :
getStringValuesSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return String
String stringValue = prefs.getString('stringValue');
return stringValue;
}
getBoolValuesSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return bool
bool boolValue = prefs.getBool('boolValue');
return boolValue;
}
getIntValuesSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return int
int intValue = prefs.getInt('intValue');
return intValue;
}
getDoubleValuesSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return double
double doubleValue = prefs.getDouble('doubleValue');
return doubleValue;
}
After you adding a new package. You have to run
flutter pub get
Then rebuild you app.
for my case add setMockInitialValues({}) before sharedPreference.getInstance worked for me
SharedPreferences.setMockInitialValues({});
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
await sharedPreferences.setString(key, value);

Flutter SharedPreferences value to Provider on applcation start

I'm trying to to set a value from sharedpreferences to provider at application start.
this what I have so far, sharedpreferences to widget is working:
https://gist.github.com/andraskende/a19c806aeef0ce88e9a9cafa49660ab4#file-main-dart-L211-L223
Finally i figured out with trial and error... It can be done in the constructor as:
class BarcodeProvider with ChangeNotifier {
BarcodeProvider() {
setup();
}
void setup() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String url = (await prefs.getString('url') ?? '');
_url = url;
notifyListeners();
}
......
}
// global variable, that can be accessed from anywhere
SharedPreferences sharedPrefs;
void main() async { // make it async
WidgetsFlutterBinding.ensureInitialized(); // mandatory when awaiting on main
sharedPrefs = await SharedPreferences.getInstance(); // get the prefs
// do whatever you need to do with it
runApp(MyApp()); // rest of your app code
}