官方网址:
https://api.flutter.dev/flutter/widgets/Navigator-class.html
在Flutter中,页面间的跳转用Navigator,通过Route 对象实现从一个页面到另一个页面的跳转。
在安卓平台上,当跳转到另一个页面时,UI上自动有一个后退按钮。其他平台通过 AppBar 上也会有一个后退按钮。
返回实现的代码为:
Navigator.pop(context);
可以定义命名路由:
void main() {
runApp(MaterialApp(
home: MyAppHome(), // becomes the route named '/'
routes: <String, WidgetBuilder> {
'/a': (BuildContext context) => MyPage(title: 'page A'),
'/b': (BuildContext context) => MyPage(title: 'page B'),
'/c': (BuildContext context) => MyPage(title: 'page C'),
},
));
}
当需要跳转时,使用下面的语句,实现跳转功能。
Navigator.pushNamed(context, '/b');
在实现路由功能时,也可以传值。
bool value = await Navigator.push(context, MaterialPageRoute<bool>(
builder: (BuildContext context) {
return Center(
child: GestureDetector(
child: Text('OK'),
onTap: () { Navigator.pop(context, true); }
),
);
}
));
上面实现的是等待用户返回一个true布尔值。
Navigator的各种用法
popAndPushNamed
销毁当前页面并跳转指向新的页面
Popup routes
像showDialog, showMenu, and showModalBottomSheet 类似模式窗口,在对话框或菜单中等待用户的进一步操作。
PopupMenuButton and DropdownButton 可以选择内容,自动进行管理。
PageRouteBuilder 类可以实现自定义路由。
Navigator.push(context, PageRouteBuilder(
opaque: false,
pageBuilder: (BuildContext context, _, __) {
return Center(child: Text('My PageRoute'));
},
transitionsBuilder: (___, Animation<double> animation, ____, Widget child) {
return FadeTransition(
opacity: animation,
child: RotationTransition(
turns: Tween<double>(begin: 0.5, end: 1.0).animate(animation),
child: child,
),
);
}
));
Nesting Navigators 嵌套路由。
import 'package:flutter/material.dart';
// ...
void main() => runApp(const MyApp());
// ...
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Code Sample for Navigator',
// MaterialApp contains our top-level Navigator
initialRoute: '/',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => const HomePage(),
'/signup': (BuildContext context) => const SignUpPage(),
},
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return DefaultTextStyle(
style: Theme.of(context).textTheme.headline4!,
child: Container(
color: Colors.white,
alignment: Alignment.center,
child: const Text('Home Page'),
),
);
}
}
class CollectPersonalInfoPage extends StatelessWidget {
const CollectPersonalInfoPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return DefaultTextStyle(
style: Theme.of(context).textTheme.headline4!,
child: GestureDetector(
onTap: () {
// This moves from the personal info page to the credentials page,
// replacing this page with that one.
Navigator.of(context)
.pushReplacementNamed('signup/choose_credentials');
},
child: Container(
color: Colors.lightBlue,
alignment: Alignment.center,
child: const Text('Collect Personal Info Page'),
),
),
);
}
}
class ChooseCredentialsPage extends StatelessWidget {
const ChooseCredentialsPage({
Key? key,
required this.onSignupComplete,
}) : super(key: key);
final VoidCallback onSignupComplete;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onSignupComplete,
child: DefaultTextStyle(
style: Theme.of(context).textTheme.headline4!,
child: Container(
color: Colors.pinkAccent,
alignment: Alignment.center,
child: const Text('Choose Credentials Page'),
),
),
);
}
}
class SignUpPage extends StatelessWidget {
const SignUpPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
// SignUpPage builds its own Navigator which ends up being a nested
// Navigator in our app.
return Navigator(
initialRoute: 'signup/personal_info',
onGenerateRoute: (RouteSettings settings) {
WidgetBuilder builder;
switch (settings.name) {
case 'signup/personal_info':
// Assume CollectPersonalInfoPage collects personal info and then
// navigates to 'signup/choose_credentials'.
builder = (BuildContext context) => const CollectPersonalInfoPage();
break;
case 'signup/choose_credentials':
// Assume ChooseCredentialsPage collects new credentials and then
// invokes 'onSignupComplete()'.
builder = (BuildContext _) => ChooseCredentialsPage(
onSignupComplete: () {
// Referencing Navigator.of(context) from here refers to the
// top level Navigator because SignUpPage is above the
// nested Navigator that it created. Therefore, this pop()
// will pop the entire "sign up" journey and return to the
// "/" route, AKA HomePage.
Navigator.of(context).pop();
},
);
break;
default:
throw Exception('Invalid route: ${settings.name}');
}
return MaterialPageRoute<void>(builder: builder, settings: settings);
},
);
}
}
// Run this example with flutter run --route=/signup
// to start it with the signup flow instead of on the home page.
onGenerateRoute:它在打开命名路由时可能会被调用。当调用 Navigator.pushNamed(…) 打开命名路由时,如果指定的路由名在路由表中已注册,则会调用路由表中的 builder 函数来生成路由组件;如果路由表中没有注册,才会调用 onGenerateRoute 来生成路由。
State Restoration