Flutter: How to read preferences at Widget startup?

initState() is a synchronous function where you cannot mark async, as async convert that function into asynchronous.

Below code helps to load shared preference values at loading time, and used to update widgets.

@override
  void initState() {
    super.initState();
    SharedPreferences.getInstance().then((prefValue) => {
      setState(() {
        _name = prefValue.getString('name')?? "";
        _controller = new TextEditingController(text: _name);
      })
    });
  }

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.

Tags:

Dart

Flutter