dart – Flutter如何使用Future返回值,就像变量一样
发布时间:2020-12-14 14:50:15 所属栏目:百科 来源:网络整理
导读:我想获得Future返回值并像变量一样使用它. 我有这个Future函数 FutureUser _fetchUserInfo(String id) async { User fetchedUser; await Firestore.instance .collection('user') .document(id) .get() .then((snapshot) { final User user = User(snapshot)
我想获得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类.它说动态. 解决方法
您可以简化代码:
Future<User> _fetchUserInfo(String id) async { User fetchedUser; var snapshot = await Firestore.instance .collection('user') .document(id) .get(); return User(snapshot); } 你还需要async / await来获取值 void foo() async { final user = await _fetchUserInfo(id); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |