繁体   English   中英

未来<bool> function 返回 null 值 flutter</bool>

[英]Future<bool> function returns null value flutter

在发布之前,我查看了以前的问题(因为有很多),但我没有找到适合我需要的东西。

我有一个 function 检查 Firestore 上是否存在文档,然后如果文档存在,则 function 必须返回 false,否则如果不存在,则为 true。

问题是 function 的返回总是 null 并且编译器告诉我 function 没有返回语句,但我不明白为什么。

这是代码,重要的 function 是checkMissingId另一个只是检查字符串id是否具有有效格式。

代码:

bool checkStr(String id, String letter, String str) {
  if (id.length < 1) {
    print("Id is too short");
    return false;
  } else {
    if ('a'.codeUnitAt(0) > letter.codeUnitAt(0) ||
        'z'.codeUnitAt(0) < letter.codeUnitAt(0)) {
      print("User name begins with bad word!");
      return false;
    }
    print("ids/tabs/" + letter);
    return true;
  }
}

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 {
      await FirebaseFirestore.instance.collection("ids/tabs/" + letter).doc(str).get()
          .then((DocumentSnapshot documentSnapshot) { //Maybe here!(??)
        if (documentSnapshot.exists) {
          print("Document exists!");
          return false;
        } else {
          print('Document does not exist on the database');
          return true;
        }
      });
    } catch (e) {
      await showErrDialog(context, e.code);
      return false;
    }
  }
}

尝试这个:

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) {
          print("Document exists!");
          return false;
        } else {
          print('Document does not exist on the database');
          return true;
        }
    } catch (e) {
      await showErrDialog(context, e.code);
      return false;
    }
  }
}

问题是在 .then .then(...) function 中,它需要一个 function 作为输入。 所以,你将无法返回任何东西。 因为它不会将数据返回到您的 function。

问题是您同时使用await.then()从 Firestore 获取数据。 用此替换您的 function 以获得所需的结果:

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 {
      DocumentSnapshot documentSnapshot = await FirebaseFirestore.instance.collection("ids/tabs/" + letter).doc(str).get();
      if (documentSnapshot.exists) {
        print("Document exists!");
        return false;
      } else {
        print('Document does not exist on the database');
        return true;
      }
    } catch (e) {
      await showErrDialog(context, e.code);
      return false;
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM