Get the Global Context in Flutter

Viewed 19280

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.

2 Answers

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}");
    

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)

Related