Search code examples
flutterbloc

Flutter: Access BlocProvider with a GlobalKey


Here's my BlocProvider (inside 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(),)
      )
    }
}

Inside MainApp, I have a widget called App, where I try to access 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
    
  }
}

The reason I do this is because when my app launches when users press a notification, I want to navigate to a certain page, but to do that I first have to call a certain Bloc event.


Solution

  • as you have mentioned you want to get the bloc and call its events,I think you just needs to simply find it by BlocProvider.of() inside Appstate class, here is the code:

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

    pls let me know if it solved your problem