颤抖如何像变量一样使用Future返回值
问题内容:
我想获取Future
返回值并像变量一样使用它。我有这个Future
功能
Future<User> _fetchUserInfo(String id) async {
User fetchedUser;
await Firestore.instance
.collection('user')
.document(id)
.get()
.then((snapshot) {
final User user = User(snapshot);
fetchedUser = user;
});
return fetchedUser;
}
我想像这样获得价值
final user = _fetchUserInfo(id);
但是当我试图这样使用
new Text(user.userName);
Dart无法识别为User
班级。它说dynamic
。
我如何获得返回值并使用它?
首先我做错了吗?任何帮助表示赞赏!
问题答案:
您可以简化代码:
Future<User> _fetchUserInfo(String id) async {
User fetchedUser;
var snapshot = await Firestore.instance
.collection('user')
.document(id)
.get();
return User(snapshot);
}
您还需要异步/等待来获取值
void foo() async {
final user = await _fetchUserInfo(id);
}