加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读