1

My app makes multiple requests to the server. Sometimes the server may ask the user to re-login, similar to this question: Flutter: how to force an application restart (in production mode)?

I could do something like this,

      Navigator.pushAndRemoveUntil(
          context,
          MaterialPageRoute(builder: (context) => LoginPage()),
          (Route<dynamic> route) => false);

but I need to have a BuildContext for this.

Is there a way to get a current (most recently used) context while in a non-Widget class? I know I can pass the context as an argument every time I'm making a server call, but I hope to find a less intrusive way to do this.

Yevgeniy Gendelman
  • 1,095
  • 1
  • 9
  • 18
  • Each widget has its own `context`, assigned during the build phase. What criteria determines which of them is the "most recently used" one? – Abion47 May 04 '19 at 00:04
  • If you need the context, you have to pass it. – Hosar May 04 '19 at 00:24

1 Answers1

1

The reason you are looking for context is because you'd like to get hold of the Navigator. (All the Navigator.pushXXX calls do a Navigator.of(context) under the hood to find the (typically) one and only navigator up near the top of the widget tree.)

If what you really want is just access to the navigator, there's another way to do this. Make your app stateful and put a global key in its state.

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

In the app's build (or top inherited widget's build), when you create the material app, pass it the key.

  @override
  Widget build(BuildContext context) {
    return _SomeInherited(
      data: this,
      child: MaterialApp(
        navigatorKey: navigatorKey,
        title: 'Some Title',
        theme: someTheme,
        home: FrontPage(),
      ),
    );
  }

Now, from the level of the app, you can use navigatorKey.currentState.pushXXX

Richard Heap
  • 48,344
  • 9
  • 130
  • 112