首页 > 解决方案 > 我怎样才能在飞镖中获得期货最终价值?

问题描述

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

  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 应该是字符串“这个组名被采用,尝试不同的”但它变为空我认为未来的构建器由于某种原因无法工作:(

标签: flutterdartasynchronousfutureflutter-futurebuilder

解决方案


您应该尝试使用 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);

推荐阅读