FlutterflutterFlutter

Flutter Bloc实现原理

2021-12-17  本文已影响0人  出来遛狗了

Bloc

大致流程

image.png

源码解读

BlocProvider

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

class BlocProvider<T extends BlocBase<Object?>>
extends SingleChildStatelessWidget with BlocProviderSingleChildWidget 
Bloc

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

class CounterBloc extends Bloc<CounterEvent, CounterState> {
  CounterBloc() : super(const CounterInitial(0)) {

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

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

abstract class Bloc<Event, State> extends BlocBase<State> {
...
final _eventController = StreamController<Event>.broadcast();

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

abstract class BlocBase<State> {

StreamController<State>? __stateController;
StreamController<State> get _stateController {
return __stateController ??= StreamController<State>.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<E extends Event>中的监听回调

 _eventController.stream.where((event) => event is E).cast<E>(),
      (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<State>(currentState: this.state, nextState: state));
    _state = state;
    _stateController.add(_state);
    _emitted = true;
  }
BlocBuilder

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

return BlocListener<B, S>(
      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;
    });
  }
上一篇下一篇

猜你喜欢

热点阅读