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
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:
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.
Create the class. Here it named as NavigationService
import ‘package:flutter/material.dart’;
class NavigationService {
static GlobalKey navigatorKey =
GlobalKey();
}
Set the navigatorKey property of MaterialApp in the main.dart
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: NavigationService.navigatorKey, // set property
)
}
Great! Now you can use anywhere you want e.g.
print("—print context:
${NavigationService.navigatorKey.currentContext}");
now you in your project like following