BlocBuilder BlocListener BlocConsumer
这三个类都是基于Stream实现的,这三个单独使用,最终实现的效果就是state改变,调用自己的setState方法。
Stream注册
void _subscribe() {
_subscription = _bloc.stream.listen((state) {
if (widget.listenWhen?.call(_previousState, state) ?? true) {
widget.listener(context, state);
}
_previousState = state;
});
}
Stream取消
void _unsubscribe() {
_subscription?.cancel();
_subscription = null;
}
BlocListener<B, S>(
bloc: _bloc,
listenWhen: widget.buildWhen,
listener: (context, state) => setState(() => _state = state),
child: widget.build(context, _state),
);
BlocProvider是基于Provider实现的,最终生成的是
_InheritedProviderScope是一个InheriteWidget类型,坐的也是InheriteWidget该做的的事情,数据共享。主要职责就是给BlocBuilder,BlocListener,BlocConsumer提过数据.
当BlocBuilder,BlocListener,BlocConsumer没有自己设置Bloc,那么就会通过 read的方式查找BlocProvider提供的Bloc
_bloc = widget.bloc ?? context.read<B>();
context.select<B, bool>((bloc) => identical(_bloc, bloc));