4

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(),
    );
  }
}

For workaround, I add those event at login as well, but it will cause multiple request for fresh login.

  • 1
    Probably, after logging in, you go to the specific page in your app - call your BLoC functions from there and not during the bloc's initialisation. – mkobuolys Feb 18 '23 at 14:07

1 Answers1

0

What about linking the bloc method:

 ..add(const FetchList())
 ..add(const UpdateCount()),

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:

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>(),
           ),
      ],
      child: const AppView(),
    );
  }
}

I assumethat you're using Firebase for authentication, and so, you can do something like this:

   FirebaseAuth.instance.authStateChanges().listen((User? user) {
     if(user != null) {
        final yourBloc = // here you get the cubit either by direct access with   getIt<ListBloc>() of with context.read<ListBloc>(), based on your case.
     
      yourBloc
       ..add(const FetchList())
       ..add(const UpdateCount()),     } 
    }

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.

Gwhyyy
  • 7,554
  • 3
  • 8
  • 35