Sobes.tech
Junior

How is basic navigation implemented in Flutter?

sobes.tech AI

Answer from AI

Navigation in Flutter is performed using the Navigator widget and its stack of pages. Each page in the app is represented as a Route.

Basic navigation includes:

  1. Pushing (adding a page): Adding a new route to the stack, making it the current page.
  2. Popping (removing a page): Removing the current route from the stack, returning to the previous page.

Examples of usage:

Adding a page with Navigator.push():

// Navigate to a new page MyHomePage
Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => const MyHomePage()),
);

Adding a page with a named route using Navigator.pushNamed():

// Navigate to a page with the named route '/second'
Navigator.pushNamed(context, '/second');

To use named routes, they need to be registered in the MaterialApp or CupertinoApp widget:

MaterialApp(
  initialRoute: '/', // Starting route
  routes: {
    '/': (context) => const FirstScreen(), // Main page
    '/second': (context) => const SecondScreen(), // Second page
  },
);

Removing the current page with Navigator.pop():

// Return to the previous page
Navigator.pop(context);
How is basic navigation implemented in Flutter… - sobes.tech