flutterdart

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.


Solution

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