Andrii Kovalchuk
Andrii Kovalchuk

Reputation: 1047

How to get name of the current route?

I need to get my current route name. I use GlobalKey to create navigatorSevice instead Navigator.of(context) in every page. So I create navKey:

class Keys {
    static final GlobalKey<NavigatorState> navKey = GlobalKey<NavigatorState>();
}

And when I want to redirect to another page, I write Keys.navKey.currentState.pushNamed() or pushReplacementNamed or some another methods.

I want to know my current route in Interceptor, where I don't have a context.

Upvotes: 8

Views: 11219

Answers (1)

Brendan
Brendan

Reputation: 1167

You already have access to BuildContext from GlobalKey<NavigatorState>().

Here - navKey.currentContext, plug it in like this - ModalRoute.of(navKey.currentContext).settings.name.

But this would fail, i'd recommend making the navKey property a getter. You can do this..

final App = Helper.I;

class Helper {
    static Helpers get I => Helpers._();

    Helpers._();

    GlobalKey<NavigatorState> get navKey => GlobalKey<NavigatorState>();
    
    BuildContext get context => navKey.currentContext;

    double get height => MediaQuery.of(context).size.height;

    double get width => MediaQuery.of(context).size.width;
}

This way, you always have access to BuildContext anywhere in you app (even in your business logic).

Usage - App.context or App.width (for device width)

Upvotes: 0

Related Questions