I want to save user preferences using Flutter\'s SharedPreference
. But the registered preferences are ALL null at new start (when app have been closed, not unis
import 'package:shared_preferences/shared_preferences.dart';
class MySharedPreferences {
MySharedPreferences._privateConstructor();
static final MySharedPreferences instance =
MySharedPreferences._privateConstructor();
setStringValue(String key, String value) async {
SharedPreferences myPrefs = await SharedPreferences.getInstance();
myPrefs.setString(key, value);
}
Future<String> getStringValue(String key) async {
SharedPreferences myPrefs = await SharedPreferences.getInstance();
return myPrefs.getString(key) ?? "";
}
Future<bool> containsKey(String key) async {
SharedPreferences myPrefs = await SharedPreferences.getInstance();
return myPrefs.containsKey(key);
}
removeValue(String key) async {
SharedPreferences myPrefs = await SharedPreferences.getInstance();
return myPrefs.remove(key);
}
removeAll() async{
SharedPreferences myPrefs = await SharedPreferences.getInstance();
return myPrefs.clear();
}
}
For more reference: Flutter Shared Preferences Tutorial
Hi I also faced the same issue. Did so many things. nothing helped .This may help someone.First thing ,followed this url and did the changes
1.https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects
2.Run the command flutter upgrade
3.Changed the shared preferences plugin in pubspec.yaml file
shared_preferences: ">=0.5.10 <2.0.0"
4.Deleted the pub cache from installed flutter location
C:\Users\myuser\AppData\Local\Pub\Cache\hosted\pub.dartlang.org
5.flutter build apk --debug
6.flutter build apk --profile
7.flutter run --release (if I run directly this command its throwing error like debug.jar not found , so I ran command 5 and 6 )
Command 7 is for - To Verify whether its working perfectly in release mode.
Finally I tried to generate app build without shrinking the code. then it worked
flutter build apk --no-shrink flutter build appbundle --no-shrink
I had the same issue and fixed it in Android/../MainActivity.java by adding at the top:
import io.flutter.plugins.GeneratedPluginRegistrant;
As well as under super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
The problem comes from using
SharedPreferences.setMockInitialValues({});
I got it from Flutter Test MissingPluginException but it seems to clear all the shared preferences.
However if you remove SharedPreferences.setMockInitialValues({});
and you don't have the two lines above in MainActivity.java, you'll get:
MissingPluginException(No implementation found for method getAll on channel flutter: plugins.flutter.io/shared_preferences)
I hope it helps!