How to globally listen from a flutter bloc?

Viewed 988

I'm implementing notifications on my app.

I have a Cubit that will emit states when the app receives a new notification.

This is my main:

class MyApp extends StatelessWidget {

 @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
        providers: [
          ...
          BlocProvider<NotificationCubit>(
              create: (context) => sl<NotificationCubit>())
        ],
        child: MaterialApp(
          home: Splash(),
          onGenerateRoute: Routes.sailor.generator(),
          navigatorKey: Routes.sailor.navigatorKey,
        ));
  }
}

I'm using get_it for dependency injection.

I tried to add BlocBuilder<NotificationCubit, NotificationState> to my home screen and it works every time the user receives the notification.

My goal is to handle the notification globally. I tried to add a listener when I create the cubit, but this doesn't work:

BlocProvider<NotificationCubit>(
          create: (context) => sl<NotificationCubit>()..listen((state) {
              if (state is NotificationReceived){
                  print("Notificaton received");
              }
           }))
1 Answers

I have heard that using get_it with bloc is not a good idea...

Especially in your case, where you are providing a bloc for the whole widget tree. Try to provide bloc without using get_it because you will have access to it in the whole app anyways.

Here there is an interesting video about it: https://youtu.be/THCkkQ-V1-8?t=6393

Related