flutter - 未来函数返回空值颤动
问题描述
在发布之前,我查看了以前的问题(因为有很多),但我没有找到适合我需要的东西。
我有一个函数可以检查 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;
}
}
}
解决方案
尝试这个:
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(...)
函数中,它需要一个函数作为输入。所以,你将无法返回任何东西。因为它不会将数据返回给您的函数。
推荐阅读
- python - 如何读取空格分隔的文本以使用 networkx 创建图形
- android - 无法在 android studio 的测试类中找到用于 Appium 测试的按钮
- c# - 从文件名中获取日期部分并使用 c# 根据最新日期进行排序
- python - 删除 numpy 数组 Python 的 nan 部分
- windows - Visual Studio Code 的终端不工作
- php - 从匿名子函数中获取父函数的名称
- c++ - 不同平面上不同大小的两条线段之间最近的两个 3D 点(已解决)
- c++ - 运行 C++ 代码后,集成终端 VSCode 不显示运行时
- python - pandas to_csv 将丢失 NaN 和 None 之间的信息
- python - 如何卸载 gfortran10