Flutter Bloc实现原理

Bloc

大致流程

image.png

源码解读

BlocProvider

1、继承SingleChildStatelessWidget,就是一个widget,通过create 传入一个Bloc对象

class BlocProvider>
extends SingleChildStatelessWidget with BlocProviderSingleChildWidget 
Bloc

1、Bloc继承自BlocBase,BlocBase中创建了StreamController对象,为多订阅对象
其中on((event, emit)为初始化创建_eventController监听

class CounterBloc extends Bloc {
  CounterBloc() : super(const CounterInitial(0)) {

    ///建立_eventController通知监听
    on((event, emit) {
      if (event is CounterEventTest) {
        emit.call(CounterInitial(event.count));
      }
    });
  }
}

2、Bloc中创建_eventController,为事件通知

abstract class Bloc extends BlocBase {
...
final _eventController = StreamController.broadcast();

3、BlocBase创建_stateController,为状态刷新通知

abstract class BlocBase {

StreamController? __stateController;
StreamController get _stateController {
return __stateController ??= StreamController.broadcast();
}

4、add方法是执行广播通知

void add(Event event) {
    if (_eventController.isClosed) return;
    try {
      onEvent(event);
        /// 广播通知
      _eventController.add(event);
    } catch (error, stackTrace) {
      onError(error, stackTrace);
    }
  }

///void on中的监听回调

 _eventController.stream.where((event) => event is E).cast(),
      (dynamic event) {
        void onEmit(State state) {
          if (isClosed) return;
          if (this.state == state && _emitted) return;
          onTransition(Transition(
            currentState: this.state,
            event: event as E,
            nextState: state,
          ));
          emit(state)

5、处理完数据之后执行emit()方法,其中emit方法是stateController广播

 void emit(State state) {
    if (_stateController.isClosed) return;
    if (state == _state && _emitted) return;
    onChange(Change(currentState: this.state, nextState: state));
    _state = state;
    _stateController.add(_state);
    _emitted = true;
  }
BlocBuilder

1、 BlocBuilder继承自BlocBuilderBase,_BlocBuilderBaseState中build方法返回的是BlocListener

return BlocListener(
      bloc: _bloc,
      listenWhen: widget.buildWhen,
        ///传入子视图监听刷新界面方法
      listener: (context, state) => setState(() => _state = state),
      child: widget.build(context, _state),
    );

2、BlocListener继承BlocListenerBase,_BlocListenerBaseState中_subscribe()添加监听stateController广播通知

void _subscribe() {
    _subscription = _bloc.stream.listen((state) {
      if (widget.listenWhen?.call(_previousState, state) ?? true) {
        ///执行父组件的listener,执行setState刷新父组件
        widget.listener(context, state);
      }
      _previousState = state;
    });
  }

你可能感兴趣的:(Flutter Bloc实现原理)