在 QuerySnapshot 中,它有“Day1”和“Day2”,它们都是像“星期六”一样的星期几。如果“Day1”或“Day2”是今天,我需要返回“true”。但是这个方法总是返回false。我需要知道为什么 If 条件(循环内)不起作用,我该如何解决这个问题?
bool class_count(Stream<QuerySnapshot> stream) {
bool class_ = false;
String dateFormat = DateFormat('EEEE').format(DateTime.now());
//This Line Return Day Like "Saturday"
stream.forEach((element) {
if (element != null) {
for (int count = 0; count < element.documents.length; count++) {
if (element.documents[count].data['Day1'].toString() == dateFormat)
class_ = true;
if (element.documents[count].data['Day2'].toString() ==
dateFormat) if (element.documents[count].data['Day2']
.toString() ==
dateFormat) class_ = true;
}
}
});
print(class_);
return class_;
}
答案 0 :(得分:3)
因为流的 forEach
是异步的。所以这个循环在它完成时不会等待。在您的代码中,您将 class_
设置为 false
,然后创建一个 future
,将在未来执行,并立即返回 classs_
。所以它仍然等于false
。
尝试在方法中添加 async
后缀,并在 await
之前添加 stream.forEach
。然后你的方法必须返回 Future<bool>
并被调用为
final class = await class_count(someStream);
我认为处理流事件的最好方法是为流添加侦听器并处理其中的数据。
stream.listener((event) {
// here must be your code which will be executed each time stream will get event
});
答案 1 :(得分:0)
stream.forEach()
方法返回一个未来类型值。所以你必须在另一个异步函数中调用这个方法,并且它需要等待直到未来完成。
解决方案:-
通过
将您的class_count()
同步方法转换为异步方法
async
关键字。Future<bool>
。在 await
方法调用前添加 stream.forEach()
关键字(异步操作)。
代码:-
[仔细阅读评论,正确理解程序流程]
//1- Return type should be a Future type => Future<bool>.
//2- Add async keyword before method body => async.
Future<bool> class_count(Stream<QuerySnapshot> stream) async{
bool class_ = false;
String dateFormat = DateFormat('EEEE').format(DateTime.now());
//3 - Adding await keyword before asynchronous operation => await.
//
await stream.forEach((element) {
if (element != null) {
for (int count = 0; count < element.documents.length; count++) {
if (element.documents[count].data['Day1'].toString() == dateFormat)
class_ = true;
if (element.documents[count].data['Day2'].toString() ==
dateFormat) if (element.documents[count].data['Day2']
.toString() ==
dateFormat) class_ = true;
}
}
});
//After stream.forEach() method completes its loop these below statements will execute.
//Every statements inside the function body will only execute one after another.
//so below statements are only executes after the above operation completes.
print(class_);
return class_;
}
一个额外的提示:- 通过使用 StreamSubcription,您可以获得数据流,而不是未来。