Muhammad Tameem Rafay
Muhammad Tameem Rafay

Reputation: 4575

Get the Global Context in Flutter

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 want the context of MaterialApp.

Upvotes: 41

Views: 59175

Answers (4)

V S
V S

Reputation: 1

Just wrap with GetMaterialApp and when you can use Get.context! to use context Anywhere

Upvotes: 0

prenszuko
prenszuko

Reputation: 55

If you use Getx State Management you can use;

GetMaterialApp(
      navigatorKey: Get.key,  
    );

Reach out with;

  BuildContext? context = Get.key.currentContext;

Upvotes: 1

Muhammad Tameem Rafay
Muhammad Tameem Rafay

Reputation: 4575

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

Upvotes: 101

Shubhamhackz
Shubhamhackz

Reputation: 7963

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)

Upvotes: 20

Related Questions