Martin Schultz
Martin Schultz

Reputation: 2861

Calling Navigator.of anywhere without context?

I've been setting up a tabbed navigation app based on this wonderful tutorial (https://medium.com/coding-with-flutter/flutter-case-study-multiple-navigators-with-bottomnavigationbar-90eb6caa6dbf).

Now I would like to display a modal overlay login route that covers the whole screen. My login controller checks if the user is logged in and I would like to fire an event on which the modal login route appears. The problem I have is now, that I don't have a context object where I receive the signal to display the login route:

Navigator.of(context).pushReplacementNamed('/');

How can I solve this or is this the wrong approach?

My User controller is a singleton object that gets initiated at app start. It checks then the user data model and if that is not set, it wants to invoke the login screen / route.

Thanks for any pointer in the right direction. Martin

Upvotes: 0

Views: 1491

Answers (3)

Mojtaba Ghiasi
Mojtaba Ghiasi

Reputation: 983

Define a navigator key that accesses from everywhere in-app (e.g in main class global space ) and pass it to root MaterialApp navigator key property in the build method

final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();

then :

  @override
  Widget build(BuildContext context) {

    return MaterialApp(
              navigatorKey: navigatorKey,
        //...
    );
}

then you can access context everywhere with doing like this:

navigatorKey.currentContext

example of navigating:

Navigator.of(navigatorKey.currentContext).pushReplacement(
  MaterialPageRoute(builder: (_) => SecondScreen()));

Upvotes: 3

ALEXANDER LOZANO
ALEXANDER LOZANO

Reputation: 2034

you can use this package to skip the required context. https://pub.dev/packages/one_context

// go to second page using named route
OneContext().pushNamed('/second');
// go to second page using MaterialPageRoute
OneContext().push(MaterialPageRoute(builder: (_) => SecondPage()));

Upvotes: 1

roipeker
roipeker

Reputation: 1243

You could use a globalKey to access the context of the widget u like (you have to pass it a key in the constructor) , and leave it in the global space, or static in any class.... although not the most elegant approach, should work

Upvotes: 1

Related Questions