我有一个屏幕,上面有一些关于用户的信息。
在我的构建小部件中,我有这个:
Column
(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>
[
Text('User Points', style: TextStyle(color: Colors.blueAccent)),
Text('${this.user.points}', style: TextStyle(color: Colors.black, fontWeight: FontWeight.w700, fontSize: 34.0))
],
),
而且我有一个功能,可以在每次用户访问时更新仪表板。
void updateDashboard() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
var api_key = prefs.getString('api_key');
var userID = prefs.getInt('userID');
var res = await http.post(('http://myApp.com/getDashboardPreferences/'+userID.toString() + '/' + api_key),
headers: {
"Accept": "application/json",
"content-type": "application/json"
});
this.user = User.fromJson(json.decode(res.body));
setState(() {
if (res.statusCode == 200) {
this.user.setPoints(this.user.points);
} else {
print("Something is wrong");
}
});
}
在 initstate 中我调用了这个函数:
@override
void initState() {
updateDashboard();
super.initState();
}
这有效,但是,我得到 ${this.user.points}
是 null
几秒钟(我得到那个警告屏幕)然后它已加载,一切正常。我想这是因为我的函数是 async
...但是我如何确保在渲染 Widget build()
之前调用此 updateDashboard()
> ?
最佳答案
如果你不想使用 FutureBuilder
那么你可以做类似的事情
if(done)
Column( /* whatever */ )
else
Center(child: CircularProgressIndicator())
void updateDashboard() async{
/* whatever */
if (res.statusCode == 200) {
setState(() {
this.user.setPoints(this.user.points);
done = true;
});
}
@override
void initState() {
/* whatever */
done = false;
}
关于dart - 如何确保在构建 Widget 之前加载异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55939288/