Want to shared Preferences null on Startup in flutter? There’s no need to put static functions in a class – just declare them as top level functions. Also, you don’t really want _myBool to be a global – it should be part of a Widget’s state. That way when you update it, Flutter knows what parts of your tree to redraw.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; void main() => runApp(new MyApp()); class MyApp extends StatefulWidget { MyApp({Key key}) : super(key: key); @override createState() => new MyAppState(); } const EdgeInsets pad20 = const EdgeInsets.all(20.0); const String spKey = 'myBool'; class MyAppState extends State<MyApp> { SharedPreferences sharedPreferences; bool _testValue; @override void initState() { super.initState(); SharedPreferences.getInstance().then((SharedPreferences sp) { sharedPreferences = sp; _testValue = sharedPreferences.getBool(spKey); // will be null if never previously saved if (_testValue == null) { _testValue = false; persist(_testValue); // set an initial value } setState(() {}); }); } void persist(bool value) { setState(() { _testValue = value; }); sharedPreferences?.setBool(spKey, value); } @override Widget build(BuildContext context) { return new MaterialApp( home: new Scaffold( body: new Center( child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Padding( padding: pad20, child: new Text( _testValue == null ? 'not ready' : _testValue.toString()), ), new Padding( padding: pad20, child: new RaisedButton( child: new Text('Save True'), onPressed: () => persist(true), ), ), new Padding( padding: pad20, child: new RaisedButton( child: new Text('Save False'), onPressed: () => persist(false), ), ), new Padding( padding: pad20, child: new RaisedButton( child: new Text('Print myBool'), onPressed: () => print(_testValue), ), ), ], ), ), ), ); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.