源码篇:Flutter Bloc背后的思想,一篇纠结的文章 (3)

BlocBase

abstract class BlocBase<State> { BlocBase(this._state) { Bloc.observer.onCreate(this); } StreamController<State>? __stateController; StreamController<State> get _stateController { return __stateController ??= StreamController<State>.broadcast(); } State _state; bool _emitted = false; State get state => _state; Stream<State> get stream => _stateController.stream; @Deprecated( 'Use stream.listen instead. Will be removed in v8.0.0', ) StreamSubscription<State> listen( void Function(State)? onData, { Function? onError, void Function()? onDone, bool? cancelOnError, }) { return stream.listen( onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError, ); } 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; } @mustCallSuper void onChange(Change<State> change) { Bloc.observer.onChange(this, change); } @mustCallSuper void addError(Object error, [StackTrace? stackTrace]) { onError(error, stackTrace ?? StackTrace.current); } @protected @mustCallSuper void onError(Object error, StackTrace stackTrace) { Bloc.observer.onError(this, error, stackTrace); assert(() { throw BlocUnhandledErrorException(this, error, stackTrace); }()); } @mustCallSuper Future<void> close() async { Bloc.observer.onClose(this); await _stateController.close(); } }

上面的BlocBase做了几件比较重要的事,来梳理下

Bloc.observer这个不重要,这是框架内部定义的一个类,这边可以忽略掉,不太重要

储存了传入的state对象

每次使用emit刷新的时候,会将传入state替换之前存储state对象

emit做了一个判断,如果传入state和存储state对象相同,将不执行刷新操作(这就是我在State类里面,加clone方法的原因)

初始化了Stream一系列对象

封装了关闭Stream流的操作

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwsxyx.html