skip to Main Content

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

2

Answers


  1. In Flutter, accessing BuildContext outside of the widget tree is generally not recommended, as it can lead to issues related to the widget lifecycle and the Flutter framework’s assumptions about widget hierarchies. However, if you need to access the BuildContext from a non-widget class, you can consider using a GlobalKey or another mechanism to pass the BuildContext to the class.

    For your specific case, if you want to access the Bloc without passing BuildContext, you can consider using a global key or a static method to hold a reference to the BuildContext. Here’s an example using a global key:

    import 'package:flutter/material.dart';
    import 'package:flutter_bloc/flutter_bloc.dart';
    
    class TestBloc extends Bloc<TestEvent, TestState> {
      TestBloc() : super(const TestInitial(false)) {
        on<TestEvent1>((event, emit) {});
      }
    
      static final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
    
      static TestBloc bloc() => BlocProvider.of<TestBloc>(navigatorKey.currentContext!);
    }
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          navigatorKey: TestBloc.navigatorKey,
          home: BlocProvider(
            create: (context) => TestBloc(),
            child: MyHomePage(),
          ),
        );
      }
    }
    
    class MyHomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: ElevatedButton(
              onPressed: () {
                final testBloc = TestBloc.bloc();
                // Use testBloc here
              },
              child: Text('Access Bloc'),
            ),
          ),
        );
      }
    }
    

    In this example, the navigatorKey is used to hold a reference to the BuildContext. This key is set in the MaterialApp widget, and then you can use it to access the BuildContext within your TestBloc class.

    Keep in mind that using global keys or static methods to access the BuildContext should be done with caution, and you need to be aware of the potential pitfalls related to the widget lifecycle in Flutter.

    Login or Signup to reply.
    1. Create the class. Here it named as NavigationService

      import ‘package:flutter/material.dart’;

      class NavigationService {
      static GlobalKey navigatorKey =
      GlobalKey();
      }

    2. Set the navigatorKey property of MaterialApp in the main.dart

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

    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); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search