-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Description
As explained in #4161, the listener will only start to listen to events after initState has executed, which may lead to situations where events are not reflected in the screen.
In order to avoid this, we need to add some extra boilerplate in initState to only call our bloc/cubit initialization/load method in addPostFrameCallback.
In order to simplify this I would like to propose that Bloc and Cubit should expose a method onAttach to be optionally overridden. This method could be simply the private StreamController.onListen only firing once.
This will add a lifecycle to Bloc and Cubit, which plays well with the current close.
onAttach can be used for initialisations that need to happen once, when the Bloc/Cubit is added into a Widget and is being listened to.
Here's a simple implementation suggestion:
// ....
BlocBase(this._state) {
// ignore: invalid_use_of_protected_member
_blocObserver.onCreate(this);
_stateController.onListen(
() {
if (!_isAttached) {
_isAttached = true;
onAttach();
}
},
);
}
// ....
bool _isAttached = false;
// ....
@protected
@visibleForTesting
void onAttach();