我们看看往bloc中添加数据流程,以demo为例
void _incrementCounter() {
_counter++;
BlocProvider.of<TestBloc>(context).add(LoadTestEvent(_counter));
}
我们调用了BlocProvider获取对应的Bloc ,然后调用他的add方法
void add(Event event) {
assert(() {
final handlerExists = _handlers.any((handler) => handler.isType(event));
if (!handlerExists) {
final eventType = event.runtimeType;
throw StateError(
'''add($eventType) was called without a registered event handler.\n'''
'''Make sure to register a handler via on<$eventType>((event, emit) {...})''',
);
}
return true;
}());
try {
onEvent(event);
_eventController.add(event);
} catch (error, stackTrace) {
onError(error, stackTrace);
rethrow;
}
}
这里首先会判断存不存在对应的handler ,如果不存在则直接报错
然后onEvent这里没做什么事 我们可以在bloc重新该方法 在对应的event发生时进行额外处理
然后调用_eventController添加到Stream里面 这里会触发我们前面一文讲到的在on方法中的listen回调
final subscription = _transformer(
_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);
}
final emitter = _Emitter(onEmit);
final controller = StreamController<E>.broadcast(
sync: true,
onCancel: emitter.cancel,
);
void handleEvent() async {
void onDone() {
emitter.complete();
_emitters.remove(emitter);
if (!controller.isClosed) controller.close();
}
try {
_emitters.add(emitter);
await handler(event as E, emitter);
} catch (error, stackTrace) {
onError(error, stackTrace);
rethrow;
} finally {
onDone();
}
}
handleEvent();
return controller.stream;
},
).listen(null);
也就是这一段中间的处理代码
这里会把onEmit包裹到_Emitter类里面,定义了一个handleEvent并最终调用他
handleEvent中调用前面_Emitter的add方法,然后调用handler处理event,handler就是我们bloc中的处理方法
TestBloc() : super(TestState()) {
//获取用户的孩子
on<LoadTestEvent>(
(event, emit) async {
emit(TestSuccessState('Hello'+event.type.toString()));
return;
},
);
}
这里的处理方法里面调用了emit函数,具体就是_Emitter的call方法
@override
void call(State state) {
assert(
!_isCompleted,
'''\n\n
emit was called after an event handler completed normally.
This is usually due to an unawaited future in an event handler.
Please make sure to await all asynchronous operations with event handlers
and use emit.isDone after asynchronous operations before calling emit() to
ensure the event handler has not completed.
**BAD**
on<Event>((event, emit) {
future.whenComplete(() => emit(...));
});
**GOOD**
on<Event>((event, emit) async {
await future.whenComplete(() => emit(...));
});
''',
);
if (!_isCanceled) _emit(state);
}
_emit就回到了前面的onEmit
final subscription = _transformer(
_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);
}
final emitter = _Emitter(onEmit);
final controller = StreamController<E>.broadcast(
sync: true,
onCancel: emitter.cancel,
);
void handleEvent() async {
void onDone() {
emitter.complete();
_emitters.remove(emitter);
if (!controller.isClosed) controller.close();
}
try {
_emitters.add(emitter);
await handler(event as E, emitter);
} catch (error, stackTrace) {
onError(error, stackTrace);
rethrow;
} finally {
onDone();
}
}
handleEvent();
return controller.stream;
},
).listen(null);
在onEmit首先判断state跟上次发送的是不是一样的,通过重新state的operator ==我们可以改变他的判断条件
class TestSuccessState extends TestState {
String data;
TestSuccessState(this.data);
@override
List<Object?> get props => [data];
// @override
// bool operator ==(Object other) {
// return false;
// }
}
回到上面 如果state是一样的或者已经发送过 则直接返回
onTransition没有做什么 然后调用emit方法
void emit(State state) {
try {
if (isClosed) {
throw StateError('Cannot emit new states after calling close');
}
if (state == _state && _emitted) return;
onChange(Change<State>(currentState: this.state, nextState: state));
_state = state;
_stateController.add(_state);
_emitted = true;
} catch (error, stackTrace) {
onError(error, stackTrace);
rethrow;
}
}
这里主要是调用了_stateController的add方法,_stateController的listen是在BlocBuilder中listen的
static VoidCallback _startListening(
InheritedContext<StateStreamable?> e,
StateStreamable value,
) {
final subscription = value.stream.listen(
(dynamic _) => e.markNeedsNotifyDependents(),
);
return subscription.cancel;
}
这里的e是InheritedProviderScope<TestBloc?>,当时的代码堆栈,
这里我们看看 e.markNeedsNotifyDependents(),
@override
void markNeedsNotifyDependents() {
if (!_isNotifyDependentsEnabled) {
return;
}
markNeedsBuild();
_shouldNotifyDependents = true;
}
markNeedsBuild最终又会引发组件的build重构