Search code examples
flutterdartblocflutter-bloc

Can we access Bloc without Passing Buildcontext param


I am migrating to GetX to Bloc, in GetController we don't need BuildContext to call controller, so is there any way to Provide the Context to the bloc class from BlocProvider and we get bloc without providing buildContext like for example:

BlocProvider(
create: (context) => TestBloc(context),
),
class TestBloc extends Bloc<TestEvent, TestState> {
  final BuildContext context;

  TestBloc(this.context) : super(const TestInitial(false)) {
    on<TestEvent1>((event, emit) {});
  }
  static TestBloc bloc() => BlocProvider.of<TestBloc>(context); //<--- Instance members can't be accessed from a static method.
// I want to access bloc without BuildContext
}

Calling the bloc

final testBloc = TestBloc.bloc();

I need this because i want to navigate the user from notification tap and there we don't have

BuildContext

Solution

    1. Create the class. Here it named as NavigationService

      import 'package:flutter/material.dart';

       class NavigationService { 
         static GlobalKey<NavigatorState> navigatorKey = 
         GlobalKey<NavigatorState>();
       }
      
    2. Set the navigatorKey property of MaterialApp in the main.dart

      Widget build(BuildContext context) { return MaterialApp( navigatorKey: NavigationService.navigatorKey, ) }

    3. Great! Now you can use anywhere you want e.g.

      print("---print context: ${NavigationService.navigatorKey.currentContext}");

    now you in your project like following

     static TestBloc bloc() => BlocProvider.of<TestBloc>(NavigationService.navigatorKey.currentContext);