首页 > 解决方案 > 未来函数返回空值颤动

问题描述

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

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

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

这是代码,重要的功能是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;
    }
  }
}

标签: flutterdartasynchronous

解决方案


尝试这个:

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(...)函数中,它需要一个函数作为输入。所以,你将无法返回任何东西。因为它不会将数据返回给您的函数。


推荐阅读