Flutter- Firestore Bloc

时间:2018-09-26 17:54:32

标签: flutter

我想知道如何为Bloc实现Firestore模式。
Bloc用于从默认默认应用中递增的应用时,会像这样。

class IncrementBloc implements BlocBase {

  int _counter;


  StreamController<int> _counterController = StreamController<int>();
  StreamSink<int> get _inAdd => _counterController.sink;
  Stream<int> get outCounter => _counterController.stream;


  StreamController<int> _actionController = StreamController<int>();
  StreamSink<int> get incrementCounter => _actionController.sink;

  IncrementBloc() {
    _counter = 0;
    _actionController.stream.listen(_handleLogic);
  }

  void _handleLogic(data) {
    _counter += 1;
    _inAdd.add(_counter);
  }

  @override
  void dispose() {
    _counterController.close();
    _actionController.close();
  }
}

问题是如何为Firestore实现此逻辑。 例如,如果我想在用户获得新关注者时更新徽章值,则必须侦听Firestore文档的新创建。但是我不知道如何创建涵盖这些内容的Bloc Firestore版本,但找不到。 我该如何在Bloc中收听 有人告诉我如何创建吗?

1 个答案:

答案 0 :(得分:0)

下面这样的方法应该适合您,只需在要显示该值的页面上添加侦听器

class IncrementBloc implements BlocBase {

  int _counter;

  StreamController<int> _counterController = StreamController<int>();
  StreamSink<int> get _inAdd => _counterController.sink;
  Stream<int> get outCounter => _counterController.stream;


  StreamController<int> _actionController = StreamController<int>();
  StreamSink<int> get incrementCounter => _actionController.sink;

  IncrementBloc() {
    // Get the latest value from firebase and listen to stream
    countAPI.getNumber().then(number) {
      _counter = number;
      _inAdd(_counter);
    });
    _actionController.stream.listen(_handleLogic);
  }

  void _handleLogic(data) async {
    _counter += 1;
    await countAPI.updateNumber(_counter); // this updates firebase
  }

  @override
  void dispose() {
    _counterController.close();
    _actionController.close();
  }
}

class APIs {
  Future<int> getNumber() async {
    try {
      // Get number from firebase
    } catch (e) {
      // Error
    }
  }

  Future<void> updateNumber() async {
    // Firebase upload 
  }
}

APIs countAPI = APIs();