如何在Flutter中仅加载一次异步流? [英] How to load async Stream only one time in Flutter?
本文介绍了如何在Flutter中仅加载一次异步流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从Firebase获得了一个普通的DocumentSnapshots流,然后使用asyncMap()方法从中生成另一个流:
I get a normal Stream of DocumentSnapshots from Firebase, and from it I generate another stream with the asyncMap() method :
final _dataBaseReference = FirebaseFirestore.instance;
Future<Stream> getPersonalShiftsbyDay() async {
//the first, normal stream
Stream firstStream = Stream<DocumentSnapshot> _personalShifts =
_dataBaseReference.doc("personalScheduledShift/$_empId").snapshots();
// the second stream, obtained with asyncMap
return _personalShifts.asyncMap((event) async {
_shiftDetails = {};
await Future.forEach(event.data().keys, (key) async {
DocumentSnapshot _shiftDoc = await _dataBaseReference
.doc("/scheduledShift/$_busId/scheduledshift/$key")
.get();
DocumentSnapshot _shiftEvents = await _dataBaseReference
.doc("/scheduledShiftEvents/$_busId/events/$key")
.get();
DocumentSnapshot _shiftEmployees = await _dataBaseReference
.doc("/scheduledShiftEmployee/$_busId/employee/$key")
.get();
_shiftDetails["${_shiftDoc.id}"] = {
"id": _shiftDoc.id,
"day": _shiftDoc.data()["day"].toDate(),
"startHour": _shiftDoc.data()["startHour"].toDate(),
"endHour": _shiftDoc.data()["endHour"].toDate(),
"events": _eventsId.length,
"employees": _employeesId,
};
});
print(_shiftDetails);
return _shiftDetails;
});
}
问题是,例如,当我在StreamBuilder中使用secondStream时,每次加载屏幕时,secondStream都会重新加载并等待 asyncMap
中包含的代码,加载一段时间并生成应用程序变慢.
The problem is, when I use the secondStream, for example in a StreamBuilder, every time I load the screen the secondStream reloads and awaits for the code contained in asyncMap
, loading for a while and making the app slower.
所以我的问题是:如何加载一次asyncMap代码(在启动应用程序时,甚至可能仅加载一次),然后将Stream用作普通流,仅当db中的数据发生更改时才发送事件?
推荐答案
您正在这样做吗?
build() {
return StreamBuilder(stream: getPersonalShiftsbyDay(), ...);
}
您应该这样做
Stream _stream;
initState() {
...
_stream = getPersonalShiftsbyDay();
}
build() {
return StreamBuilder(stream: _stream, ...);
}
要了解更多信息:
https://youtu.be/vPHxckiSmKY?t=4772
这篇关于如何在Flutter中仅加载一次异步流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文