【问题标题】:Future still returns null FlutterFuture 仍然返回 null Flutter
【发布时间】:2021-02-19 16:54:05
【问题描述】:

我有一个调用Future<bool> 函数的函数:

bool checkId(String id, context) {
  bool ret;
  checkMissingId(id, context).then((value) => ret = value);
  return ret;

那叫:

Future<bool> checkMissingId(String id, context) async {
  String str = id.toLowerCase();
  String letter = str[0];
  if (checkStr(id, letter, str) == false)
    return false; //checks some rules on strings
  else {
    try {
      var data = await FirebaseFirestore.instance
          .collection("ids/tabs/" + letter)
          .doc(str)
          .get();
      if (data.exists) {
        return false;
      } else
        return true;
    } catch (e) {
      await showErrDialog(context, e.code);
      return false;
    }
  }
}

ret 返回null,而不是布尔值。

编辑:checkId 的类型必须是 bool,而不是 Future&lt;bool&gt;

【问题讨论】:

    标签: flutter dart asynchronous


    【解决方案1】:

    因为checkId函数返回时是null。您应该等待操作,如下所示:

    Future<bool> checkId(String id, context) async {
      bool ret = await checkMissingId(id, context);
      return ret;
    }
    

    【讨论】:

    • 我希望 checkId 不是 Future 类型,而只是 bool。
    • 您可以使用waitFor,但它是实验性的,根本不建议使用。无论如何,真的没有理由不使用异步。
    【解决方案2】:

    在返回ret 变量之前,您需要暂停程序的执行以使checkMissingId 方法完成。为此,您可以使用 await 关键字并将函数标记为 async

    您应该将代码更改为:

    Future<bool> checkId(String id, context) async {
      bool ret = await checkMissingId(id, context);
      return ret;
    }
    

    【讨论】:

    • 我希望 checkId 为 bool,而不是 Future
    • 您正在checkId 内部进行异步调用。返回类型必须是Future。您是否有任何特殊原因希望它成为 bool 返回类型?
    • 是的,我会做一个新的帖子更清楚
    猜你喜欢
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多