Flutter: How to read preferences at Widget startup?

前端 未结 2 605
眼角桃花
眼角桃花 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:22

    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 {
      TextEditingController _controller;
      String _name;
    
      Future 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.

提交回复
热议问题