我使用从 InitState() 调用的方法,在那里用 await 加载 SP。但是 Widget 在加载 SP 之前正在构建并且具有空的 SP 值。
void getSP() async {
var prefs = await SharedPreferences.getInstance();
_todoItems = prefs.getStringList("key") ?? _todoItems;
}
Run Code Online (Sandbox Code Playgroud)
完整代码:https : //pastebin.com/EnxfKgPH
有很多选择,我喜欢的是使用这样的布尔变量
bool isLoaded = false;
@override
void initState() {
getSP();
super.initState();
}
void getSP() async {
var prefs = await SharedPreferences.getInstance();
_todoItems = prefs.getStringList("key") ?? _todoItems;
setState(() => isLoaded = true);
}
Run Code Online (Sandbox Code Playgroud)
然后检查它以确定构建树是否应该加载,就像这样..
@override
Widget build(BuildContext context) {
return !isLoaded ? CircularProgressIndicator() : Scaffold(
appBar: new AppBar(title: new Text('Todo List')),
body: _buildTodoList(),
floatingActionButton: new FloatingActionButton(
backgroundColor: Theme.of(context).primaryColor,
onPressed: _pushAddTodoScreen,
// pressing this button now opens the new screen
tooltip: "Add task",
child: new IconTheme(
data: new IconThemeData(color: Colors.black87),
child: new Icon(Icons.add),
),
),
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
399 次 |
| 最近记录: |