32

Is there any way to get the global context of Material App in Flutter. Not the context of particular screen.

I am trying to get the context but it gives me the context of particular screen but I wan the context of MaterialApp.

Muhammad Tameem Rafay
  • 3,602
  • 2
  • 21
  • 32

3 Answers3

77

If above solution does not works please try this 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, // set property
      )
    }
    
  3. Great! Now you can use anywhere you want e.g.

    print("---print context: 
      ${NavigationService.navigatorKey.currentContext}");
    
Muhammad Tameem Rafay
  • 3,602
  • 2
  • 21
  • 32
18

Assign a GlobalKey() to the MaterialApp which you can put in a separate class, let's call it App :

 @override
    Widget build(BuildContext context) {
      return MaterialApp(
        navigatorKey: App.materialKey, // GlobalKey()
      )
    }

Now wherever you want to get the context of the MaterialApp, you just have to call :

App.materialKey.currentContext

Here I'm printing MaterialApp context :

print('Material App Context : ${App.materialKey.currentContext}'); 

OUTPUT : flutter: Material App Context : MaterialApp-[GlobalKey#4fab4](state: _MaterialAppState#4bb44)

Shubhamhackz
  • 7,333
  • 7
  • 50
  • 71
  • 2
    Am new to flutter where do you get the App class as mine still doesnt have. – Geoff Sep 18 '21 at 13:00
  • 2
    Is there a scenario where using a GlobalKey to get access to BuildContext is discouraged? To push a new route or show a SnackBar or a dialog, a BuildContext is required. To avoid passing BuildContext instances as arguments, I'd like to use the BuildContext of the GlobalKey. But I wonder if there's something I need to watch out for. One example of a bad use of global context I've thought of is dynamic InheritedWidget lookups. – SametSahin Sep 21 '21 at 22:08
  • 2
    @Geoff its a class you build on your own, see the second answer https://stackoverflow.com/a/69299440/9528391 – evals Dec 03 '21 at 04:25
3

If you use Getx State Management you can use;

GetMaterialApp(
      navigatorKey: Get.key,  
    );

Reach out with;

  BuildContext? context = Get.key.currentContext;
prenszuko
  • 49
  • 2