3

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");
              }
           }))
0

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I changed sl<NotificationCubit>() to NotificationCubit( messaging: FirebaseMessaging(), localNotifications: FlutterLocalNotificationsPlugin()), but the problem still persist. I use get_it only to initialize blocs. When I need to access to them I use context.read() / context.watch()...
+1 for that video, it totally changed everything for me. Very long at 3.5 hours, but that's a testament to how complicated the topic is. Every minute was very valuable. Thanks!
1

To globally listen to a bloc you need to put it above MaterialApp

return MultiBlocProvider(
        providers: [
          ...
          BlocProvider<NotificationCubit>(
              create: (context) => NotificationCubit()),
        ],
        child: Builder(
            builder: (context) =>
                BlocListener<NotificationCubit, NotificationState>(
                  listener: (context, state) {
                    ...
                  },
                  child: MaterialApp(
                  ...
                  )
        )),
);

Remember to use Builder or create another stateless class after using BlocProvider

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.