简体   繁体   English

如何从 flutter 集团全局收听?

[英]How to globally listen from a flutter bloc?

I'm implementing notifications on my app.我正在我的应用程序上实施通知。

I have a Cubit that will emit states when the app receives a new notification.我有一个 Cubit 会在应用程序收到新通知时发出状态。

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.我正在使用get_it进行依赖注入。

I tried to add BlocBuilder<NotificationCubit, NotificationState> to my home screen and it works every time the user receives the notification.我尝试将BlocBuilder<NotificationCubit, NotificationState>添加到我的主屏幕,并且每次用户收到通知时它都会起作用。

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

I have heard that using get_it with bloc is not a good idea...我听说将 get_it 与 bloc 一起使用不是一个好主意......

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.尝试在不使用 get_it 的情况下提供 bloc,因为无论如何您都可以在整个应用程序中访问它。

Here there is an interesting video about it: https://youtu.be/THCkkQ-V1-8?t=6393这里有一个有趣的视频: https://youtu.be/THCkkQ-V1-8?t=6393

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM