So I have a BLoC which I need to access globally through my app - CurrentUserBloc and its purpose is to hold data of currently logged in user. It can hold some states like CurrentUserWaiting, CurrentUserReady, CurrentUserError etc. Some of them hold user instance - like CurrentUserReady, and some don't - like CurrentUserWaiting. Now I need to access this user data in order to send an event to another BLoC. For example I want to post a photo and I need userId of currently logged in user to do this. But I can't just use BlocProvider.of<CurrentUserCubit>(context).state.user to get user data because some of this bloc's states - like CurrentUserWaiting - don't store user property and compiler won't take this.
I get around it by creating abstract state class CurrentUserWithUserInstance and extending it in states that hold user property. Then I just access state like this:
final currentState = BlocProvider.of<CurrentUserCubit>(context).state
as CurrentUserWithUserInstance;
Then I get user property from this and use it to add event in another BLoC.
I was wondering what would be a better way to do this. I need to access user data in multiple places in the app and I don't know if this is a good approach. I know I could use just one state class with all properties and then change it by copyWith method. By that doesn't really seem that good to me.
How do you store and access global state using BLoC?