I’m providing bloc at top of all view to access at globally. When I’m doing logout and re-login without closing app, event not called because it is already initiate. Here, I want to refresh bloc on logout, so that FetchList and UpdateCount events got called when user logged In without closing app. How I can achieve this?
class DemoApp extends StatelessWidget {
const DemoApp({super.key});
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(create: (_) => AppBloc()..add(const UpdateFcmToken())),
BlocProvider(
create: (_) => getIt<ListBloc>()
..add(const FetchList())
..add(const UpdateCount()),
),
],
child: const AppView(),
);
}
}
2
Answers
What about linking the bloc method:
with the authentication stream that you’re using in your app, I mean instead of calling the methods manually when creating the bloc, what about doing only this:
I assumethat you’re using Firebase for authentication, and so, you can do something like this:
and so now, you won’t need to worry about doing it manually, since every time a new user with authenticate (
user != null
), the events will be emited.You can achieve this by listening for a logout event and then resetting the ListBloc. You can create a new event in your ListBloc for this purpose, say ResetListBloc, and call it when the user logs out. This will cause the Bloc to re-initialize and fetch the list and update count as required.
First, add a new event called ResetListBloc in your ListBloc:
Now, modify your ListBloc to handle this event:
Finally, in your logout process, add the ResetListBloc event to your ListBloc:
By adding this event, you ensure that when the user logs out, the ListBloc is reset, and the FetchList and UpdateCount events are called when the user logs in again without closing the app.