5

我正在使用颤振从少数设备交换 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
    });
  }

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

¿ 有什么建议吗?

非常感谢。

J.巴勃罗。

4

1 回答 1

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

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

于 2019-06-19T15:30:34.210 回答