Flutter Navigator not working

Just make the MaterialApp class in main method as this example

 void main() => runApp(MaterialApp(home: FooClass(),));

it works fine for me, I hope it will work with you


There are two main reasons why the route cannot be found.

1) The Route is defined below the context passed to Navigator.of(context) - scenario which @rmtmackenzie has explained

2) The Route is defined on the sibling branch e.g.

Root 

  -> Content (Routes e.g. Home/Profile/Basket/Search)

  -> Navigation (we want to dispatch from here)

If we want to dispatch a route from the Navigation widget, we have to know the reference to the NavigatorState. Having a global reference is expensive, especially when you intend to move widget around the tree. https://docs.flutter.io/flutter/widgets/GlobalKey-class.html. Use it only where there is no way to get it from Navigator.of(context).

To use a GlobalKey inside the MaterialApp define navigatorKey

final navigatorKey = GlobalKey<NavigatorState>();

Widget build(BuildContext context) => MaterialApp {
    navigatorKey: navigatorKey
    onGenerateRoute : .....
};

Now anywhere in the app where you pass the navigatorKey you can now invoke

navigatorKey.currentState.push(....);

Just posted about it https://medium.com/@swav.kulinski/flutter-navigating-off-the-charts-e118562a36a5


Think of the widgets in Flutter as a tree, with the context pointing to whichever node is being built with the build function. In your case, you have

MainScreen    <------ context
  --> MaterialApp
   (--> Navigator built within MaterialApp)
      --> Scaffold
        --> App Bar
          --> ...
        --> Center
          --> FlatButton

So when you're using the context to find the Navigator, you're using a context for the MainScreen which isn't under the navigator.

You can either make a new Stateless or Stateful Widget subclass to contain your Center + FlatButton, as the build function within those will point at that level instead, or you can use a Builder and define the builder callback (which has a context pointing at the Builder) to return the Center + FlatButton.

Tags:

Dart

Flutter