Flutter:如何在Widget启动时读取首选项?

Roc*_*ole 10 dart flutter

我一直试图在Widget启动时读取首选项,但一直无法找到解决方案.我希望在TextField中显示用户名(他们可以更改)并将其存储在首选项中,以便在它们返回页面时立即显示.

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,
             )
  }
}
Run Code Online (Sandbox Code Playgroud)

我在initState()上使用async的想法来自:
API调用后有状态小部件上的颤动定时问题
但async似乎在启动时导致此错误:

'package:flutter/src/widgets/framework.dart': Failed assertion: line 967 pos 12: 
'_debugLifecycleState == _StateLifecycle.created': is not true.
Run Code Online (Sandbox Code Playgroud)

我查找了FutureBuilder的示例,但似乎找不到任何类似于我想要做的事情.

Mah*_*ahi 18

我建议不要在initState()上使用async.但是你可以通过将SharedPreferences包装在另一个函数中并将其声明为异步来以不同的方式执行此操作.

我修改了你的代码.请检查一下是否有效.非常感谢.

修改后的代码

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,
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

如果这有帮助,请告诉我.谢谢.