以下是我的BLocProvider(在MainApp内):

final keyBlocProvider =
        GlobalKey<NavigatorState>(debugLabel: "BlocProvider Navigator");

class MainApp extends StatelessWidget {
  const MainApp({super.key});
  
  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
        key: keyBlocProvider, // I'm trying to access BlocProvider with this key
        providers: [
          BlocProvider<ClockBloc>(
            create: (_) => ClockBloc(),
          ),
        ],
        child: MaterialApp(home: const App(),)
      )
    }
}

MainApp内部,我有一个名为App的小部件,我try 在其中访问BlocProvider outside of my build function:

class _AppState extends State<App> {
  @override
  Widget build(BuildContext context) {}
  
  /// Process notification when loading the app
  void onNotificationListener(String? payload) {
    var context = Navigator.of(keyBlocProvider.currentContext!).context; // my app freezes here
    
  }
}

我这样做的原因是,当我的应用程序在用户按下通知时启动时,我想导航到某个页面,但要做到这一点,我首先必须调用某个Bloc事件.

推荐答案

正如您提到的,您希望获取块并调用其事件,我认为您只需通过AppState类中的BlocProvider.of()找到它,以下是代码:

_clockBloc = BlocProvider.of<ClockBloc>(context);
_clockBloc.add(YourEvent());

如果它解决了你的问题,请告诉我

Flutter相关问答推荐

如何在列表磁贴上添加行

如何让GridView.builder用另外两个小部件来占据屏幕的剩余部分

在Riverpod ConsumerWidget中使用文本编辑控制器

错误:找不到字体功能类型.Ffltter Google_Fonts包错误

在Flutter 中将参数从一个类传递到另一个类

我的flutter代码显示一个小部件被认为是死代码,为什么?

Ffltter:发布版本中的Path NotFoundException

使用Future函数的容器中未显示图像,但在使用图像小工具时显示

如何在应用程序中使用Fflight显示表情包

有没有方法可以从当前时间轻松计算TimeStamp?

摆动更改标记可轻敲文本按钮样式

尽管海拔设置为 0,如何删除 appBar 下的下划线

如何获取flutter中gridview项目占用的高度和宽度?

Flutter Dismissible 不会在 startToEnd 滑动时被关闭

在使用 Android 12+ 的真实 Android 设备上,SingleChildScrollView 中最初位于视口之外的无响应 Web 视图

如何显示从 MariaDB 获取的数据到列表视图

为什么 orientation == Orientation.portrait 总是正确的,尽管我的设备已经处于横向

如何在屏幕按钮中排列 row() (我想在按钮中放置屏幕导航图标)

如何从dart 中的当前日期时间中减go 1 天?

如何在 ElevatedButton 上设置背景 colored颜色 动画?