dart - 如何“等待”非未来变量?
问题描述
我DocumentReference locationDocumentRef;
在我的状态。
我正在locationDocumentRef
根据参考资料进行更改,无论是通过查询还是通过添加新文档来收集。
所以我有这个功能来检查文档,如果有一个设置它对 . 的引用locationDocumentRef
,或者添加一个新的并将它的 ref 设置为locationDocumentRef
. 我每次都通过将其设置为 null 来重置它的值,因为我不想获得以前的结果。但它打印空。
所以我的问题是,我怎样才能解决它们并获得价值?我认为我在代码中解决得太早了,所以我不能等待一个非未来的值。我该如何解决?
void firestoreCheckAndPush() async {
setState(() {
locationDocumentRef = null;
});
bool nameExists = await doesNameAlreadyExist(placeDetail.name);
if (nameExists) {
print('name exist');
} else {
print('name will be pushed on firestore');
pushNameToFirestore(placeDetail);
}
var resolvedRef = await locationDocumentRef;
print(resolvedRef.documentID); // I get null here
}
这些是我使用过的功能
Future<bool> doesNameAlreadyExist(String name) async {
QuerySnapshot queryDb = await Firestore.instance
.collection('locations')
.where("city", isEqualTo: '${name}')
.limit(1)
.getDocuments();
if (queryDb.documents.length == 1) {
setState(() {
locationDocumentRef = queryDb.documents[0].reference;
});
return true;
} else {
return false;
}
}
和另一个
void pushNameToFirestore(PlaceDetails pd) async {
DocumentReference justAddedRef =
await Firestore.instance.collection('locations').add(<String, String>{
'city': '${pd.name}',
'image': '${buildPhotoURL(pd.photos[0].photoReference)}',
});
setState(() {
locationDocumentRef = justAddedRef;
});
}
解决方案
我首先在这里看到了两个错误 var resolvedRef = await locationDocumentRef; 为什么你等待 locationDocumentRef,其次你不等待 pushNameToFirestore(PlaceDetails pd) firestoreCheckAndPush() 函数,这很奇怪,因为 pushNameToFirestore(String) 是同步的,这意味着你不会等待它完成,所以如果你要添加一个新名称,它会打印空。如果我错了,请纠正我。您可以在此处找到有关同步和未来的更多信息https://www.dartlang.org/tutorials/language/futures 查看页面中间的图表
推荐阅读
- r - 在 R 的一个方面用两个可能的选项重新排序 x 轴
- c++ - 未定义模板的隐式实例化:g++ 或 clang++
- javascript - 如何删除空数组javascript中的推送项目?
- react-native - 反应本机重新选择状态未定义
- r - 为在 R 中使用 grid.arrange() 创建的每一行图赋予一个标题
- ios - M1 mbp 使用 xcode 12.5.1 使用设备“我的 mac(为 iphone 设计)”进行调试,但“在调试器附加到它之前无法启动或退出”
- r - 在闪亮的应用程序中阅读所有 Excel 工作表
- r - 将 cURL 语句转换为 HTTR
- android - 更新 gradle 包装器后无法解析类 MavenDeployment
- operating-system - 如何充分模拟 RISC-V 中的控制和状态寄存器?