dart – Flutter如何使用Future返回值,就像变量一样

前端之家收集整理的这篇文章主要介绍了dart – Flutter如何使用Future返回值,就像变量一样前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_2@
我想获得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);
}
@H_403_2@

猜你在找的Flutter相关文章