通常入口组件MyApp的格式如下:
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: const Home(),
onGenerateRoute: Routes.generateRoute,
onUnknownRoute: (_) {
return MaterialPageRoute(builder: (BuildContext context) {
return const NotFoundPage();
});
},
);
}
}
home
入口组件,默认对应命名路由的 '/' ,所以如果定义了home,命名路由中就不要定义 '/' 了。
routes
命名路由列表,格式如下所示:
return {
'/error/404': (BuildContext context) => const NotFoundPage(),
'/home': (BuildContext context, {arguments}) => Home(),
};
如果要进行路由拦截和传参,就不要传入此参数,因为传入此参数后,onGenerateRoute
不会执行。
onUnknownRoute
未知路由的处理方法,通常用于返回未找到页面的组件。
onGenerateRoute
关键属性,用于路由拦截和传参
///路由配置
static Map<String, WidgetBuilder> initRoutes() {
return {
'/error/404': (BuildContext context) => const NotFoundPage(),
'/home': (BuildContext context, {arguments}) => const Home(),
'/login': (BuildContext context) => const LoginPage()
};
}
///路由跳转拦截,支持传参
static Route<dynamic>? generateRoute(RouteSettings settings) {
final String name = settings.name ?? '';
Map<String, WidgetBuilder> routes = initRoutes();
final Function? builder = routes[name] as Function;
if (builder != null) {
if (settings.arguments != null) {
return MaterialPageRoute(builder: (BuildContext context) => builder(context, arguments: settings.arguments),settings: settings);//此处将参数传递给ModalRoute
} else {
return MaterialPageRoute(builder: (BuildContext context) => builder(context));
}
}
}
路由跳转时,传递参数:
Navigator.pushNamed(context, '/home', arguments: {"name": "张三"});
获取传递过来的参数:
Widget build(BuildContext context) {
Map? arguments = ModalRoute.of(context)?.settings.arguments as Map;
return Scaffold(
appBar: AppBar(
),
body: Text(arguments['name']),// 张三
);
}