Flutter get context from anywhere

To get the context from anywhere in a Flutter application, you can make use of the “BuildContext” class provided by Flutter. The “BuildContext” object represents the location of a widget within the widget tree, and it provides access to various methods and properties of the widget.

One common approach to accessing the context from anywhere is by using the “InheritedWidget” class. InheritedWidget is a widget base class in Flutter that allows data to be passed down the widget tree without the need for explicit callbacks or state management.

Here’s an example of how you can create a custom InheritedWidget to pass the context down the widget tree:

  
class AppContext extends InheritedWidget {
  final BuildContext rootContext;
 
  AppContext({
    Key key,
    @required this.rootContext,
    @required Widget child,
  }) : super(key: key, child: child);
 
  static AppContext of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType();
  }
 
  @override
  bool updateShouldNotify(AppContext oldWidget) => true;
}
 
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      home: AppContext(
        rootContext: context,
        child: MyHomePage(),
      ),
    );
  }
}
 
class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Access the root context from anywhere in the app
    final rootContext = AppContext.of(context)?.rootContext;
 
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: Center(
        child: Text(
          'Root Context: $rootContext',
          style: TextStyle(fontSize: 20),
        ),
      ),
    );
  }
}
 
void main() {
  runApp(MyApp());
}
  
  

In this example, we create a custom InheritedWidget called “AppContext” which holds the root context of the application. In the “MyApp” widget, we wrap the “MyHomePage” widget with the “AppContext” widget, providing the root context as a parameter. Inside the “MyHomePage” widget, we can access the root context by calling “AppContext.of(context)?.rootContext”.

By utilizing the InheritedWidget approach, the context can be accessed from anywhere within the widget tree, making it easy to pass down or retrieve information as needed.

Leave a comment