Google News
logo
Flutter - Interview Questions
What is a Flutter router and how is it used?
In Flutter, a router is a mechanism for managing navigation between different pages or screens in an app. The router maintains a stack of pages, with the topmost page being the current page displayed on the screen.

Flutter provides a built-in `Navigator` class that manages the app's navigation stack, and allows you to push and pop pages from the stack as necessary. The `Navigator` class can be accessed through the `Navigator.of(context)` method, which returns the nearest `Navigator` widget in the widget tree.

To use a router in your Flutter app, you can define a set of routes that map route names to the widgets that should be displayed when that route is requested. For example, you could define a route for a home screen, a settings screen, and a profile screen, like this:
var routes = {
  '/home': (context) => HomeScreen(),
  '/settings': (context) => SettingsScreen(),
  '/profile': (context) => ProfileScreen(),
};​
Once you have defined your routes, you can navigate to a new page using the `Navigator.pushNamed()` method, which takes the route name as an argument. For example :
Navigator.pushNamed(context, '/settings');​
This will push the `SettingsScreen()` widget onto the navigation stack and display it on the screen.

You can also pass arguments to a new screen using the `arguments` parameter of `Navigator.pushNamed()`, like this:
Navigator.pushNamed(context, '/profile', arguments: {'userId': '123'});​
In this case, the `ProfileScreen()` widget would receive a `Map` containing the `userId` argument when it is displayed.
Advertisement