一、基本路由
1. 不携带参数
//跳转到EditLogPage页面
Navigator.of(context).push(
MaterialPageRoute(builder: (contex){
return EditLogPage();
})
);
2. 携带参数
(1)不传参
Navigator.of(context).push(
MaterialPageRoute(builder: (contex){
return EditLogPage();//跳转到编辑日志页面
})
);
//编辑日志页面
class EditLogPage extends StatelessWidget{
String title;
EditLogPage({this.title="编辑"});// {}表示默认的值,可以传入参数,也可以不传参
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(this.title),
),
);
}
}
(2)携带参数
Navigator.of(context).push(
MaterialPageRoute(builder: (contex){
return EditLogPage(title:"编辑日志");//携带参数跳转到编辑日志页面
})
);
class EditLogPage extends StatelessWidget{
String title;
EditLogPage({this.title="编辑"});//这里的默认值被覆盖了
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(this.title),
),
);
}
}
3.路由跳转–浮动按钮返回
class EditLogPage extends StatelessWidget{
String title;
EditLogPage({this.title="编辑"});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(this.title),
),
floatingActionButton: FloatingActionButton(//右下角浮动按钮
child: Text("返回"),
onPressed: (){
Navigator.pop(context);//返回上一级路由
},
),
);
}
}
二、命名路由
(1)新建routs.dart
//配置路由
final routes ={
"/LoadingPage":(context) =>LoadingPage(),
'/SearchPage': (context) =>SearchPage(),
'/MenuPage': (context,arguments) =>MenuPage({arguments:arguments}),
};
//固定写法
var onGenerateRoute = (RouteSettings settings) {
// 统一处理
final String name = settings.name;
final Function pageContentBuilder = routes[name];
if (pageContentBuilder != null) {
if (settings.arguments != null) {
final Route route = MaterialPageRoute(
builder: (context) =>
pageContentBuilder(context, arguments: settings.arguments));
return route;
} else {
final Route route =
MaterialPageRoute(builder: (context) => pageContentBuilder(context));
return route;
}
}
};
(2)main.dart
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: "/LoadingPage", //初始化时候加载的路由
onGenerateRoute: onGenerateRoute,
);
}
(3)命名路由跳转
//不携带参数
Navigator.pushNamed(context, '/SearchPage');//跳转到搜索页面
//携带参数
Navigator.pushNamed(context, '/MenuPage',arguments: title);//带参跳转