我正在尝试将数据获取到Appbar的api,但是卡在await / async中
我正在尝试做的是:
getUserName(id) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String token;
token = prefs.get('Token');
String url = "https://apiurl";
http.post(
url,
headers: {'authorization': 'bearer' + token},
body: {'thread': id.toString()},
).then((response) {
print("Response body: ${response.body}");
return response.body;
});
}
我在尝试构建时将其称为:appBar: AppBar(
title: Text(getUserInfo(widget.id)),
....
但是我最终得到了:future 动态的实例
我了解我应该以某种方式等待结果。但是,如果尝试尝试,则不接受等待:
await getUserInfo(widget.id);
最佳答案
首先等待您对http.post
的 call
Future<String> getUserName(id) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String token;
token = prefs.get('Token');
String url = "https://apiurl";
var response = await http.post(
url,
headers: {'authorization': 'bearer' + token},
body: {'thread': id.toString()},
);
return response.body
}
然后可以使用这样的东西// Declare _userInfo at state class level and run this on build or initState
if (_userInfo == null) {
getUserInfo(id).then((userInfo) => setState(() => _userInfo = userInfo));
}
然后appBar: AppBar(
title: Text(_userInfo),
关于flutter - 将数据获取到appBar-Flutter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62506588/