I have been trying to read preferences at Widget startup but have been unable to find a solution. I wish to show the users name in a TextField (which they can change) and store it in preferences so that it is shown as soon as they go back to the page.
class _MyHomePageState extends State<MyHomePage> { TextEditingController _controller; : : Future<Null> storeName(String name) async { SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setString("name", name); } @override initState() async { super.initState(); SharedPreferences prefs = await SharedPreferences.getInstance(); _controller = new TextEditingController(text: prefs.getString("name")); } @override Widget build(BuildContext context) { : : return new TextField( decoration: new InputDecoration( hintText: "Name (optional)", ), onChanged: (String str) { setState(() { _name = str; storeName(str); }); }, controller: _controller, ) } }
I got the idea for using async on initState() from :
flutter timing problems on stateful widget after API call
But the async seems to cause this error on startup :
'package:flutter/src/widgets/framework.dart': Failed assertion: line 967 pos 12: '_debugLifecycleState == _StateLifecycle.created': is not true.
I looked for examples of FutureBuilder but cannot seem to find any which are similar to what I am trying to do.
A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared. This page shows you how to use the SharedPreferences APIs to store and retrieve simple values.
I would suggest not to use the async on initState(). but you can do this in a different way by wrapping up your SharedPreferences inside another function and declaring this as async.
I have modified your code . Please check if this works. Many Thanks.
modified code:
class _MyHomePageState extends State<MyHomePage> { TextEditingController _controller; String _name; Future<Null> getSharedPrefs() async { SharedPreferences prefs = await SharedPreferences.getInstance(); _name = prefs.getString("name"); setState(() { _controller = new TextEditingController(text: _name); }); } @override void initState() { super.initState(); _name = ""; getSharedPrefs(); } @override Widget build(BuildContext context) { return new TextField( decoration: new InputDecoration( hintText: "Name (optional)", ), onChanged: (String str) { setState(() { _name = str; storeName(str); }); }, controller: _controller, ); } }
Let me know if this helps. Thank you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With