I'm relatively new to flutter bloc state management, so here is the scenario where I would be needing to access state of another bloc
there are two bloc in my flutter app, the first one is UserBloc which stores user session id or token in its state (UserState) and the second one is MediaBloc, this bloc requires user session id or token to fetch the logged in user media list
User Bloc
class UserBloc extends Bloc<UserState, UserEvent>{
}
class UserState{
String token;
UserState({this.token});
}
Media Bloc
class MediaBloc extends Bloc<MediaState, MediaEvent>{
on<FetchMediaEvent>((event, state) async {
List<Media> mediaList = await fetchUserMedia(token: ''); // how to access value of token which is in UserBloc state
});
}
class MediaState{
List<Media> mediaList;
MediaState({this.mediaList});
}
class FetchMediaEvent {
}
in the doc you can see two way to do it:
You can find examples there how to do it.
But in your case, with high probability, you just need to take token when you want fetch some data. So, UserBloc
will be global. Whenever in your code you will add an FetchMediaEvent
event to the MediaBloc
you always could do this:
...
final token = context.read<UserBloc>().state.token;
context.read<MediaBloc>().add(FetchMediaEvent(token));
...
where:
class FetchMediaEvent extends MediaEvent {
const FetchMediaEvent(this.token);
final String token;
}
p.s. in your code the event and state are mixed up:
abstract class Bloc<Event, State>
should be:
class UserBloc extends Bloc<UserEvent, UserState>
p.p.s. Also, you can pass UserBloc(or stream from UserBloc) to the MediaBloc. you could listen this stream and react to every UserBloc state. But this is bad practice - it creates a dependency between two blocs. Then you have two other options described above.