What is the Purpose of Navigator
In Flutter, Navigator is a core component primarily used for navigating between screens. It manages a route stack, using a stack-based approach to handle the switching of pages (i.e., routes). When a new page is opened, it is pushed to the top of the route stack; when the user navigates back, the current page is popped from the top of the stack, revealing the previous page. This mechanism is well-suited for implementing multi-level page navigation and back functionality.
Basic Usage of Navigator
1. Navigating to a New Page:
To navigate to a new page in Flutter, you typically use the Navigator.push() method. This method pushes a new route onto the route stack, displaying the new page.
dartNavigator.push( context, MaterialPageRoute(builder: (context) => NewScreen()), );
In this example, executing this code opens the NewScreen page.
2. Returning to the Previous Page:
To return to the previous page, you typically use the Navigator.pop() method. This method removes the current route from the top of the stack, returning to the previous page.
dartNavigator.pop(context);
This is commonly used in the callback function of a back button.
3. Navigation with Parameters:
Sometimes, when navigating between pages, you need to pass data. This can be achieved by passing parameters in the MaterialPageRoute constructor.
dartNavigator.push( context, MaterialPageRoute( builder: (context) => DetailScreen(data: 'Here is the passed data'), ), );
Then, in the DetailScreen constructor, receive this data:
dartclass DetailScreen extends StatelessWidget { final String data; DetailScreen({Key key, this.data}) : super(key: key); Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Detail Page'), ), body: Center( child: Text(data), ), ); } }
Advanced Usage of Navigator
1. Named Routes:
Flutter also supports navigation using route names, which decouples navigation from specific page constructors, making the code more modular.
First, define the route names and their corresponding pages in the MaterialApp:
dartMaterialApp( routes: { '/': (context) => HomeScreen(), '/detail': (context) => DetailScreen(), }, );
Then, navigate using named routes:
dartNavigator.pushNamed(context, '/detail');
2. Replacing Routes:
In certain scenarios, such as after logging in and navigating to the home page, you might want to destroy all previous pages after navigation, in which case you can use Navigator.pushReplacement():
dartNavigator.pushReplacement( context, MaterialPageRoute(builder: (context) => HomeScreen()), );
In summary, Navigator is an essential tool in Flutter for managing page navigation, managing routes via a stack-based approach, providing flexible page navigation, data passing, and replacement capabilities, serving as the foundation for building multi-page applications.