【发布时间】:2021-05-22 14:08:20
【问题描述】:
在发布之前,我查看了以前的问题(因为有很多),但我没有找到适合我需要的东西。
我有一个函数可以检查 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;
}
}
}
【问题讨论】:
-
您在
try块中等待操作,但您永远不会返回值。顺便说一句,你为什么混合await和then语法?似乎违反直觉。 -
要获得
Future<bool>值,您应该像这样使用它:Future.value(false)
标签: flutter dart asynchronous