Route and Navigator
Basic usage
The basic use of the Navigator is to jump from one page to another and back to the first page with the back button on the second page.
Creating two pages
First, creating two pages, each containing a button. Clicking the button on the first page will navigate to the second page. Clicking the button on the second page will return to the first page.
The first page:
class FirstScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('First Screen'),
),
body: new Center(
child: new RaisedButton(
child: new Text('Launch second screen'),
onPressed: (){
//Creating routes by MaterialPageRoute and using Navigator.push() to navigate to second page.
Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new SecondScreen()),
);
},
),
),
);
}
}
The second page:
class SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Second Screen'),
),
body: new Center(
child: new RaisedButton(
child: new Text('Go back!'),
onPressed: (){
//using Navigator.pop() to return last page.
Navigator.pop(context);
}),
),
),
);
}
}
MaterialPageRoute params introduction
MaterialPageRoute({
WidgetBuilder builder,
RouteSettings settings,
bool maintainState = true,
bool fullscreenDialog = false,
})
- builder: which is a callback funciton of WidgetBuilder and to build the contents of the route. the return value is a widget. We typically implement the callback to return an instance of the new route.
- settings: Containing the configuration for the route, such as the route name, whether or not it is the original route (home page).
- maintainState: By default, when a new route is pushed, the original route is still held in memory, and maintainState can be set to false if you want to free all the resources the route occupies when it is not used.
- fullscreenDialog: whether the new routing page is a full-screen modal dialog. For iOS, if the fullscreenDialog is true, the new page will slide in from the bottom of the screen (not horizontally).
Using named navigator routes
Mobile apps often manage a large number of routes and it's often easiest to refer to them by name. Route names, by convention, use a path-like structure (for example, '/a/b/c'). The app's home page route is named '/' by default.
The MaterialApp can be created with a Map
Registered routing table
void main() {
runApp(MaterialApp(
home: MyAppHome(), // becomes the route named '/'
routes: {
'/a': (BuildContext context) => MyPage(title: 'page A'),
'/b': (BuildContext context) => MyPage(title: 'page B'),
'/c': (BuildContext context) => MyPage(title: 'page C'),
},
));
}
Opening a new routing page with the routing name
Navigator.pushNamed(context, '/b');
or
Navigator.of(context).pushNamed('/b');
Note:In addition to the pushNamed method, the Navigator also has other methods for managing named routing, such as pushReplacementNamed, so you can view the API documentation.
Routes can return a value
When a route is pushed to ask the user for a value, the value can be returned via the pop method's result parameter.
Methods that push a route return a Future. The Future resolves when the route is popped and the Future's value is the pop method's result parameter.
For example if we wanted to ask the user to press 'OK' to confirm an operation we could await the result of Navigator.push:
For example:
void skipToSelectPage() async{
//deliver arguments when jump to selectPage.
final result = await Navigator.pushNamed(context, SelecPage.routeName,
arguments: argumnets);
}
GestureDetector(
onTap: () {
//return to last page with selectedDataList
Navigator.pop(context, selectedDataList);
},
)
Custom routes
You can create your own subclass of one of the widget library route classes like PopupRoute, ModalRoute, or PageRoute, to control the animated transition employed to show the route, the color and behavior of the route's modal barrier, and other aspects of the route.
The PageRouteBuilder class makes it possible to define a custom route in terms of callbacks. Here's an example that rotates and fades its child when the route appears or disappears. This route does not obscure the entire screen because it specifies opaque: false, just as a popup route does.
Navigator.push(
context,
PageRouteBuilder(
transitionDuration: Duration(milliseconds: 500), //Animation time is 500 milliseconds.
pageBuilder: (BuildContext context, Animation animation,
Animation secondaryAnimation) {
return new FadeTransition(
//Using the fade in transition.
opacity: animation,
child: PageB(),
);
},
),
);
Nesting Navigators
An app can use more than one Navigator. Nesting one Navigator below another Navigator can be used to create an "inner journey" such as tabbed navigation, user registration, store checkout, or other independent journeys that represent a subsection of your overall application.
for example:
Create a page with two bottomNavigationBar.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/testroute/page_main_navigator.dart';
import 'package:flutter_app/testroute/page_profile.dart';
class HomePage extends StatefulWidget {
@override
State createState() {
return new _HomeState();
}
}
class _HomeState extends State {
int _currentIndex = 0;
final List _children = [
new MainNavigatorPage(),
new ProfilePage(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: _children[_currentIndex],
bottomNavigationBar: new BottomNavigationBar(
onTap: onTabTapped,
currentIndex: _currentIndex,
items: [
new BottomNavigationBarItem(
icon: new Icon(Icons.home),
title: new Text('Main'),
),
new BottomNavigationBarItem(
icon: new Icon(Icons.person),
title: new Text('Profile'),
),
],
),
);
}
void onTabTapped(int index) {
setState(() {
_currentIndex = index;
});
}
}
First page of HomePage and define two routing pages.
class MainNavigatorPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Navigator(
initialRoute: 'main',
onGenerateRoute: (RouteSettings settings) {
WidgetBuilder builder;
switch (settings.name) {
case 'main':
builder = (BuildContext context) => new MainPage();
break;
case 'demo':
builder = (BuildContext context) => new DemoPage();
break;
default:
throw new Exception('Invalid route: ${settings.name}');
}
return new MaterialPageRoute(builder: builder, settings: settings);
},
);
}
}
import 'package:flutter/material.dart';
class MainPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Home'),
),
body: new Center(
child: new RaisedButton(
child: new Text('demo'),
onPressed: () {
Navigator.of(context).pushNamed('demo');
},
),
),
);
}
}
Routing stack management in Flutter
push()
Insert an element directly into the top of the stack.
Navigator.of(context).pushNamed("/111");
Navigator.of(context).push(route);
pop()
Delete the top element of the stack and returns to the previous page.
Navigator.of(context).pop();
pushReplacementNamed()和popAndPushNamed()
There is a scenario, after jumping to Screen3, we want to jump to Screen4, but we don't want to go back to Screen3 by clicking the back button. That is, while inserting Screen4 into the top of the stack, remove Screen3.
Navigator.of(context).pushReplacementNamed('/screen4');
Navigator.popAndPushNamed(context, '/screen4');
Navigator.of(context).pushReplacement(newRoute);
pushNamedAndRemoveUntil()
Push the route with the given name onto the navigator that most tightly encloses the given context, and then remove all the previous routes until the predicate
returns true.
Pop up Screen3 and Screen2, and then push the new Screen4.
Navigator.of(context).pushNamedAndRemoveUntil('/screen4', ModalRoute.withName('/screen1'));
Be sure to delete all routes before pushing new route.
Navigator.of(context).pushNamedAndRemoveUntil('/LoginScreen', (Route
popUntil()
popUntil(RoutePredicate predicate);
Navigator.of(context).popUntil(ModalRoute.withName("/XXX"));