【发布时间】:2018-06-25 11:18:17
【问题描述】:
我一直在尝试阅读 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,
)
}
}
我得到了在 initState() 上使用异步的想法:
flutter timing problems on stateful widget after API call
但是异步似乎在启动时导致了这个错误:
'package:flutter/src/widgets/framework.dart': Failed assertion: line 967 pos 12:
'_debugLifecycleState == _StateLifecycle.created': is not true.
我查找了 FutureBuilder 的示例,但似乎找不到与我正在尝试做的类似的任何示例。
【问题讨论】: