Navigate between screens in Flutter

In Flutter, there are two main widgets used to navigate between screens:

  • A Route is an abstraction for an app screen or page.
  • A Navigator is a widget that manages routes.
  • A Navigator is defined as a widget that manages a set of child widgets with a stack discipline. The navigator manages a stack of Route objects and provides methods for managing the stack, like Navigator.push and Navigator.pop. A list of routes might be specified in the MaterialApp widget, or they might be built on the fly, for example, in hero animations. The following example specifies named routes in the MaterialApp widget.

    class NavigationApp extends StatelessWidget {
      // This widget is the root of your application.
      const NavigationApp({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          //...
          routes: {
            '/a': (BuildContext context) => UsualNavScreen(),
            '/b': (BuildContext context) => DrawerNavScreen(),
          },
          //...
        );
      }
    }
    

    To navigate to a named route, the Navigator.of() method is used to specify the BuildContext (a handle to the location of a widget in the widget tree). The name of the route is passed to the pushNamed function to navigate to the specified route.

    Navigator.of(context).pushNamed('/a');
    

    You can also use the push method of Navigator which adds the given Route to the history of the navigator that most tightly encloses the given BuildContext, and transitions to it. In the following example, the MaterialPageRoute widget is a modal route that replaces the entire screen with a platform-adaptive transition. It takes a WidgetBuilder as a required parameter.

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (BuildContext context) => UsualNavScreen(),
      ),
    );
    

    Search within Codexpedia

    Custom Search

    Search the entire web

    Custom Search