I've just changed my projects to release mode and its suddenly make my SharedPreferences doesn't work as it works before the change. The value is always return as a 'null' even I save it as 1.
This is how I save the data
_storeOnBoardInfo() async {
int isViewed = 1;
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setInt('onBoard', isViewed);
}
and this is how a load the data
void main() async {
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
statusBarColor: Colors.white, statusBarIconBrightness: Brightness.dark));
WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
isViewed = prefs.getInt('onBoard');
FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
runApp(const MyApp());
FlutterNativeSplash.remove();
}
I tried some solutions but it doesn't work for me. Is there any other way to make solve this problem?
Related
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.
I am creating a flutter app, I am using shared_preferences to store the themeMode and using provider to manage state. I am able to fetch the themeMode before my app starts but not able to run the provider function that sets the themeMode.
Following is my code
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences.getInstance().then((prefs) {
var isDarkTheme = prefs.getBool("isDarkTheme") ?? false;
return runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(
create: (_) => ThemeManager(),
),
],
child: MyApp(isDarkActive: isDarkTheme),
),
);
});
}
My Provider "State Management" code
class ThemeManager with ChangeNotifier {
bool _isDark = false;
void setThemeMode(bool themeMode) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool("isDarkTheme", themeMode);
_isDark = themeMode;
debugPrint(_isDark.toString());
notifyListeners();
// return true;
}
void fetchTheme() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var darkMode = prefs.getBool('isDarkTheme');
if (darkMode != null) {
_isDark = darkMode;
} else {
_isDark = false;
}
notifyListeners();
}
bool get isDark => _isDark;
}
You need to initialise a single global shared preference variable which you can use everywhere in your app so that you don't have to initialise it every time you when you want to use it.
so create a signleton class like this,
class SharedPreferencesHelper {
SharedPreferencesHelper._();
late SharedPreferences prefs;
Future<void> initialise() async {
prefs = await SharedPreferences.getInstance();
}
static final SharedPreferencesHelper instance = SharedPreferencesHelper._();
}
now initialise this in main() like this,
void main()async{
WidgetsFlutterBinding.ensureInitialized();
await SharedPreferencesHelper.instance.initialise();
}
now only use this variable where ever you want like this,
SharedPreferencesHelper.instance.prefs.getBool('key');
or create some functions inside your helper class,
Future<bool> getProperty(String key) async {
return await prefs.getBool(key);
}
The code is here. I add getTemporaryDirectory in main.but It make the screen white.
Future<void> main() async {
await getTemporaryDirectory();
runApp(MyApp());
}
Do this instead:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized(); // new line
await getTemporaryDirectory();
runApp(MyApp());
}
Read more about the ensureInitialized method here : WidgetsBinding ensureInitialized
I've been trying to keep the user logged in if they haven't logged out, just simple SharedPreferences stuff, but every time that I save my SP and I hot reload, or hot restart my app, the function returns null, just like it didn't save anything. I've tried literally everything but can't figure it out. This is my code:
Getting my SPs on startup
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
isLoggedIn = prefs.getBool('isLoggedIn');
Timer(Duration(milliseconds: 100), ()=>{print(isLoggedIn)});
runApp(MyApp());
}
Saving my SPs after successful user login
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('isLoggedIn', true);
bool isLoggedIn = prefs.getBool('isLoggedIn');
print(isLoggedIn);
The writing functions on Shared Preferences are asynchronus sou you need to await them.
Try await prefs.setBool('isLoggedIn', true);
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
}