gpt4 book ai didi

firebase - 在 Dart/Flutter 中,如果 Firestore 数据库中没有 Collection,如何查看?

转载 作者:IT王子 更新时间:2023-10-29 07:23:52 25 4
gpt4 key购买 nike

我想检查一个集合(users 集合)是否存在于 Firestore 数据库中。但是我找不到任何方法来做到这一点。如果该集合存在,我想流式传输其文档,否则如您在以下方法中看到的那样为空流

- 有什么方法可以在不获取快照的情况下找到一个集合?
- 为什么 break;yield* Stream.empty() 挂流,源源不断!

Stream<userInfo> getCurrentUserInfos() async* {
final String usersCollectionPath = "users";
Stream<QuerySnapshot> snapshots = Firestore.instance.collection(usersCollectionPath).snapshots();
snapshots.isEmpty.then((hasNoUserCollection) {
// Although I don't have 'users' collection
// in my database but I never reach this point!
// i.e. hasNoUserCollection is always FALSE!
if(hasNoUserCollection) {
print("users collection doesn't exist, create it!");
// next line (i.e. `break;`) hangs the tool!
// And sometimes hangs the VSCode's IDE as well, if I have a breakpoint on it!!!
break;
// I tried yielding an empty stream instead of break, again another hang!
// yield* Stream<userInfo>.empty();
} else {
// previous stream is dead, so create it again!
snapshots = Firestore.instance.collection(usersCollectionPath ).snapshots();
await for (QuerySnapshot snap in snapshots) {
for (DocumentSnapshot userDoc in snap.documents) {
yield (new userInfo.fromQuerySnapshot(userDoc));
}
}
});
}

现在,当流为空时,即使是 try-catch block 也无法捕捉到错误!

try{
getCurrentUserInfos().last.then((userInfolastOne) {
print("last one: $lastOne.name");
});

// the following line (i.e. await ...) at least doesn't hang and
// `catch` block is able to catch the error `Bad state: No element`,
// when the stream is empty
//
// userInfo lastOne = await stream.last;
} catch (ex) {
print ("ex: $ex");
}

最佳答案

没有检测集合是否存在的 API。事实上:Firestore 中的集合只有在其中有文档时才存在。

我能想到的最便宜的检查是对单个文档进行查询,然后检查该查询是否有任何结果。

关于firebase - 在 Dart/Flutter 中,如果 Firestore 数据库中没有 Collection,如何查看?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54055565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com