Flutter_bloc 在没有 UI 事件的情况下从 firestore 获取更新的数据

Jua*_*eto 5 flutter google-cloud-firestore bloc

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

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

图像描述简介

但是 flutter_bloc 是这样工作的:

脚步:

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

  2. 异步请求

  3. 异步响应

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

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

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

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

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

¿任何建议?

非常感谢。

J. 巴勃罗。

May*_*ate 4

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

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

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));
      },
    );
  }

Run Code Online (Sandbox Code Playgroud)

参考文献: 评论 1评论 2 ,作者:Felix Angelov ( felangel ),Bloc Gitter Chat 中的 flutter_bloc 库创建者