路由简介:
Navigator 管理路由的组件, Navigator 可以通过路由入栈和出栈来实现页面之间的跳转
initialToute: 初始路由,默认页面onGenerateRoute:动态路由(根据规则匹配相应路由)onUnknownRoute:未知路由,404页面routes:路由集合
匿名路由跳转
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => 路由组件Widget
)
)
路由传参

命名路由:
代码示例
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'flutter',
// home: Home(),
routes: {
'shop': (context) => Shop(),
'ShopDetail': (context) => ShopDetail()
},
initialRoute: 'shop',
onUnknownRoute: (RouteSettings settings) => MaterialPageRoute(
builder: (context) => UnknownRoute(),
),
debugShowCheckedModeBanner: false,
);
}
}
import 'package:flutter/material.dart';
class Shop extends StatelessWidget {
const Shop({ Key key }) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, 'ShopDetail');
},
child: Text('商品详情'),
),
);
}
}
class ShopDetail extends StatelessWidget {
const ShopDetail({ Key key }) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('返回'),
),
);
}
}
class UnknownRoute extends StatelessWidget {
const UnknownRoute({ Key key }) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: Text('404'),
);
}
}
注意:路由跳转使用Navigator.pushNamed(context, 'ShopDetail');, 返回使用Navigator.pop(context);
路由传参

动态路由

注意:使用onGenerateRoute 生成动态路由后,route路由表(命名路由)失效
Flutter路由管理与页面跳转详解
这篇博客详细介绍了Flutter中Navigator组件如何管理路由,包括初始路由、动态路由和未知路由的设置。通过示例代码展示了如何进行匿名路由跳转、命名路由传递参数以及返回操作。同时,文中提到了动态路由的使用会使得命名路由失效的情况。
843

被折叠的 条评论
为什么被折叠?



