【问题标题】:Flutter_bloc get updated data from firestore without UI eventFlutter_bloc 从没有 UI 事件的 firestore 获取更新的数据
【发布时间】:2019-08-18 13:46:57
【问题描述】:

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

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

但是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。巴勃罗。

【问题讨论】:

  • 您提出的解决方案在我看来基本上没问题。你最关心的是什么?
  • 每次用户触摸 UI 时,您都会得到 2 个答案:一个是 BLOC 答案流,另一个是 FireStore Collection SnapShot。

标签: flutter google-cloud-firestore bloc


【解决方案1】:

使用 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 库创建者

【讨论】:

    猜你喜欢
    • 2022-10-02
    • 1970-01-01
    • 2021-07-27
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 2020-07-01
    • 1970-01-01
    相关资源
    最近更新 更多