In Android development, interfaces correspond to activities, and we launch from one interface to another with intents. Route (Route) in mobile development usually refers to pages (Page), the so-called Route management, is to manage how to jump between pages, usually can also be called navigation management. Navigation management maintains a routing stack. Push operations open a new page, pop operations close a page, and routing management focuses on how to manage the routing stack.
First, try the knife
Write a New Route, then the main screen contains a button, click the button to jump to a New page. The new page is very simple, an AppBar + a Text.
class NewRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("New route"),
),
body: Center(
child: Text("I'am new route"),),); }}Copy the code
Next, look at the home screen that contains the code for the Raise button
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Home Page"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Click button to open new route:',
),
RaisedButton.icon(
icon: Icon(Icons.send),
label: Text("Go"),
onPressed: () {
// Navigate to the new route
Navigator.push(context, MaterialPageRoute(builder: (context) {
returnNewRoute(); })); },),],),); }}Copy the code
Here’s a GIF of what it looks like:
The code for jumping from the home screen to the new page is very simple, using the following code snippet. Let’s learn what this code means.
// navigate to the NewRoute Navigator. Push (context, MaterialPageRoute(builder: (context) {return NewRoute(); }));Copy the code
Ii. Route management
Although the code to navigate to the new route is very brief, many of the new “elements” need to be learned or it’s unclear why this code works.
2.1 the Navigator
Navigator is a routing management component that provides methods to open and exit the routing page. Navigator manages a collection of active routes through a stack. Usually the current screen is the top of the stack routing. The Navigator provides a series of methods to manage the routing stack.
Future push(BuildContext context, Route route)
Pushes the given route onto the stack (that is, opens a new page), and the return value is a Future object that receives the data returned when the new route is off the stack (that is, closed).
Future pushNamed(
BuildContext context,
String routeName, {
Object arguments,
})
Pushes the named route on the stack. Arguments takes arguments. The return value is a Future object that receives the data returned when the new route is off the stack.
bool pop(BuildContext context, [ T result ])
Route the top of the stack out of the stack. Result is the data returned to the previous page when the page closes.
Navigator has many other methods that I won’t cover.
2.2 MaterialPageRoute
The MaterialPageRoute inherits from the PageRoute class, which is an abstract class representing a modal routing page that occupies the entire screen space. It also defines interfaces and properties related to the transition animation during route construction and switching. MaterialPageRoute is a component provided by the Material component library, which can be used for different platforms to achieve routing switching animation in the same style as the platform page-switching animation:
On Android, when a new page opens, it slides from the bottom of the screen to the top of the screen; When you close the page, the current page slides from the top to the bottom of the screen and disappears, while the previous page is displayed on the screen.
On iOS, when a page is opened, the new page will slide consistently from the right edge of the screen to the left of the screen until all the new pages are displayed on the screen, while the previous page will slide from the current screen to the left of the screen and disappear. When you close the page, the opposite is true, the current page slides out from the right side of the screen, while the previous page slides in from the left.
The meanings of the parameters of the MaterialPageRoute constructor are described below:
MaterialPageRoute({
WidgetBuilder builder,
RouteSettings settings,
bool maintainState = true.bool fullscreenDialog = false,})Copy the code
Builder is a callback function of type WidgetBuilder that builds the specific content of the routed page and returns a widget. We typically implement this callback to return an instance of the new route.
Settings contains the configuration information of the route, such as the route name and whether the route is the initial route (home page).
MaintainState By default, when a new route is pushed, the original route is kept in memory. If you want to release all resources used by the route when it is not used, set maintainState to false.
FullscreenDialog indicates whether the new routing page is a full-screen modal dialog. In iOS, if fullscreenDialog is true, the new page will slide in from the bottom of the screen (rather than horizontally).
3. Name the route
Named routes give a name to a Route, and then a new Route can be opened using the name of the Route. This provides an intuitive and simple way for Route management.
3.1 the routing table
To use named routes, we must first provide and register a routing table so that the application knows which name corresponds to which routing component. The routing table is defined as follows:
Map<String, WidgetBuilder> routes;
It’s a Map, and the key is the name of the route, which is a string; Value is a Builder callback that generates the appropriate routing widget. When we open a new route with the route name, the application looks up the corresponding WidgetBuilder callback function in the routing table based on the route name, then calls the callback function to generate the route widget and returns.
3.2 Registering the Routing Table
In the Build method of MyApp class, locate the MaterialApp and add the Routes attribute “new_page” to the NewRoute route.
class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Blue,), // register routes:{"new_page":(context) => NewRoute(),}, home: MyHomePage(),); }}Copy the code
3.3 Enabling a New Route by route Name
Using the pushNamed method, the code is as follows
Navigator.pushNamed(context, "new_page");
Copy the code
We’ll see that it works exactly like the Demo above.
Iv. Route usage
Let’s examine the use of routing with a few examples.
4.1 Route Transmission Value
Modify the NewRoute code in the demo example to add a country String Field and display the corresponding content in the Text.
class NewRoute extends StatelessWidget {
NewRoute({@required this.country}) : super(a);final String country;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("New route"),
),
body: Center(
child: Text("I'am new route country=$country"),),); }}Copy the code
Modify the code in MyHomePage to look like this:
Navigator.push(context, MaterialPageRoute(builder: (context) {
return NewRoute(country:"China");
}));
Copy the code
If you look at the result, you have displayed “China” in the Text.
When you pass values with pushNamed, the effect is the same.
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
// Register the routing table
routes: {
"new_page": (context) => NewRoute(), }, home: MyHomePage(), ); }}class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Home Page"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Click button to open new route:',
),
RaisedButton.icon(
icon: Icon(Icons.send),
label: Text("Go"),
onPressed: () {
// Navigate to the new route
Navigator.pushNamed(context, "new_page", arguments: "China"); },),],),); }}class NewRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
var args = ModalRoute.of(context).settings.arguments;
return Scaffold(
appBar: AppBar(
title: Text("New route"),
),
body: Center(
child: Text("I'am new route country=$args"),),); }}Copy the code
4.2 Route Return Value
The NewRoute route adds a return button that returns the string “I am the return value” via the Navigator. Pop method. The MyHomePage Navigator. PushNamed method returns a Future object from which we receive the return value and watch the log print.
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Home Page"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Click button to open new route:',
),
RaisedButton.icon(
icon: Icon(Icons.send),
label: Text("Go"),
onPressed: () {
// Navigate to the new route
Navigator.pushNamed(context, "new_page", arguments: "China")
.then((data) {
// Accept the returned arguments
print(data.toString()); }); },),],),); }}class NewRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
var args = ModalRoute.of(context).settings.arguments;
return Scaffold(
appBar: AppBar(
title: Text("New route"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("I'am new route country=$args"),
RaisedButton.icon(
icon: Icon(Icons.arrow_back),
label: Text("Back"),
onPressed: () => Navigator.pop(context, "I am the return value"),),))); }}Copy the code
Log:
I/flutter (3996): I am the return value
Run animation:
Further, change MyHomePage1 to StatefulWidget on the home screen where the return value is displayed.
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
// Register the routing table
routes: {
"new_page": (context) => NewRoute(), }, home: MyHomePage1(), ); }}class MyHomePage1 extends StatefulWidget {
@override
_MyHomePageState1 createState() => _MyHomePageState1();
}
class _MyHomePageState1 extends State<MyHomePage1> {
String _back = "";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Home Page"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Click button to open new route:$_back',
),
RaisedButton.icon(
icon: Icon(Icons.send),
label: Text("Go"),
onPressed: () {
// Navigate to the new route
Navigator.pushNamed(context, "new_page", arguments: "China")
.then((data) {
// Accept the returned arguments
_back = data.toString();
print(_back); setState(() {}); }); },),],),); }}Copy the code
The running results are as follows: