Flutter: How to read preferences at Widget startup?

前端 未结 2 620
眼角桃花
眼角桃花 2020-12-25 14:04

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 st

2条回答
  •  鱼传尺愫
    2020-12-25 14:23

    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);
          })
        });
      }
    

提交回复
热议问题