【问题标题】:how can i get a futures final value in dart?我怎样才能在飞镖中获得期货最终价值?
【发布时间】:2021-10-26 14:24:05
【问题描述】:

我正在尝试这个,但它不起作用:

  Future<bool> isGroupNameAvailable(String name) async {
bool result = true;
(await _fireStore.collection("groups").get()).docs.forEach((doc) {
  if (name == doc.id) {
    result = false;
  }
});
return result;

}

 FutureBuilder(
                          future: db!.isGroupNameAvailable(value),
                          builder: (BuildContext context,
                              AsyncSnapshot<bool> snap) {
                            setState(() {
                              _isGidUnique = snap.data!
                                  ? null
                                  : "this group name is taken,try different one";
                            });

                            print("*************first" +
                                _isGidUnique.toString());
                            return Text("");
                          },
                        );

                        // db!
                        //     .isGroupNameAvailable(value)
                        //     .then((avilible) => setState(() {
                        //           _isGidUnique = avilible
                        //               ? null
                        //               : "this group name is taken,try different one";
                        //         }));
                        print(_isGidUnique);
                        return _isGidUnique;

_isGidUnique 应该是字符串“这个组名被占用,尝试不同的”,但它为空 我认为未来的建设者由于某种原因无法工作 帮助:(

【问题讨论】:

  • 这能回答你的问题吗? What is a Future and how do I use it?
  • 嗨,谢谢,但不是真的。我了解未来的概念,但我真的不明白为什么我的代码不起作用
  • 仔细查看 FutureBuilder 示例。您错过了 SnapShot 可能还没有数据的事实。

标签: flutter dart asynchronous future flutter-futurebuilder


【解决方案1】:

您应该尝试如下使用 Future.wait 方法:

/// Future.wait takes an array of futures and completes when they are all over
var docs = await Future.wait(_fireStore.collection("groups").get()).docs);
/// every returns true if all elements match the given predicate
return docs.every((doc) => name != doc.id);

【讨论】:

  • 您的代码未编译:参数类型“List>>”无法分配给参数类型“Iterable>”。
猜你喜欢
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
相关资源
最近更新 更多