gpt4 book ai didi

Flutter_bloc 从没有 UI 事件的 firestore 获取更新的数据

转载 作者:IT老高 更新时间:2023-10-28 12:46:40 25 4
gpt4 key购买 nike

我正在使用 Flutter 从少数设备交换 Firestore 数据。

如果我使用 StreamBuilder 一切正常,但我不喜欢将业务逻辑与 UI 混合。我更喜欢使用 BLOC 作为模式使用 flutter_bloc 插件。

introducir la descripción de la imagen aquí

但是flutter_bloc是这样工作的:

步骤:

  1. 事件 ------------------------> 新数据但没有新 UI 事件

  2. 异步请求

  3. 异步响应

  4. State (mapEventToState)-------> ¿我如何获得新的状态?

我没有“UI 事件”,因为 Firestore 数据正在从另一台设备更新,所以我无法更新状态。

我可以在 bloc 构造函数上使用类似的东西:

  Stream<QuerySnapshot> query;
QuedadaBloc(){
query = Firestore.instance.collection('my_collection').snapshots();
query.listen((datos){
dispatch(Fetch()); // send fictitious UI event
});
}

但我认为这不是正确的方法。

¿有什么建议吗?

非常感谢。

J。巴勃罗。

最佳答案

使用 Flutter、Bloc 和 Firestore 时推荐的方法是让存储库层提供来自 Firestore 的数据流,该数据流可由 Bloc 构造函数中的 Bloc(或任何其他函数;请参阅这个example)。

然后,根据流中的更改,当您在流中从 Firestore 接收到新数据时,dispatch 事件。 Bloc 可以处理触发的 dispatch 事件以在 UI 中的更改触发状态更改时以类似的方式更改应用程序的状态。

class SampleBloc extends Bloc<SampleEvent, SampleState> {
final FirestoreRepo _firestoreRepo;

StreamSubscription<?> _firestoreStreamSubscription;

SampleBloc({@required FirestoreData firestoreData})
: assert(firestoreRepo != null),
_firestoreRepo = firestoreRepo;

// instead of '_mapXEventToState', the subscription can also be wired in 'SampleBloc' constructor function.
Stream<TimerState> _mapXEventToState(XEvent xEvent) async* {
// Runs a dispatch event on every data change in Firestore
_firestoreStreamSubscription = _firestoreRepo.getDataStream().listen(
(data) {
dispatch(YEvent(data: data));
},
);
}

引用资料: Comment 1Comment 2作者:Felix Angelov (felangel),Bloc Gitter Chat 中的 flutter_bloc 库创建者

关于Flutter_bloc 从没有 UI 事件的 firestore 获取更新的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55386590/

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