I have a problem implementing an app on Flutter using flutter_bloc. I understood the core concepts but I found an "edge case" where there is not examples or guides (at least that I could find):
(I will simplify the problem) I have a bloc called AuthBloc
that manages the App
. If the state is NotAuthenticated
then the App should show the LoginScreen
but if is Authenticated
the App should show the HomeScreen
. Inside the HomeScreen
I have 4 blocs, where each bloc has its states and events, but all of them has dependencies on different Repositories
to get some data from an API.
All the Repositories
need a token to make the API requests. The first problem came here. How can I get the token from all the repositories? If I use a UserRepository
to store the token, I will need to pass it as dependency to each Repository (probably works but I don't think its the right way to do it). So, what can be the right way to manage this?
The second problem is:
If somehow I can get the token on all the repositories queries, what happens when the token is revoked? The app should return to the LoginScreen
and for that I would need to notify the AuthBloc
through an event (for example InvalidTokenEvent
). And the AuthBloc
should change its state to NotAuthenticated
and that will rebuild the LoginScreen
. But the question is: How can I notify the AuthBloc
from other blocs or repositories? The first idea I had is through dependency injection: I can pass the AuthBloc to every other bloc in the constructor, so when the repository request returns a token expired, the XBloc
can call AuthBloc.add(InvalidTokenEvent)
. But again, if I have a lot of blocs I would need to do that in each bloc. So, what's the right way to do this?
Thank you for any help!