单页面路由跳转时留神不要有两个 materialapp,因为导航是依赖于这个的,有两个,就会有两个导航
一、两种路由传参办法:DetailScreen 跳转的路由组件
- 间接向路由子组件构造函数传参
Navigator.push(
context,
MaterialPageRoute(builder: (context) => DetailScreen(todo: todos[index]),
),
);
- 通过 RouteSettings 传递参数
Navigator.push(
context,
MaterialPageRoute(builder: (context) => DetailScreen(),
settings: RouteSettings(arguments: todos[index],
),
),
);
二、定义路由:
1、在 MaterialApp 中增加属性:
initialRoute 和 routes 来定义咱们的路由
new MaterialApp(
initialRoute: '/',
routes: {'/': (context) => TodosScreen(todos: todos),
'/detail': (context) => DetailScreen(),},
title: 'ssss',
);
但要留神的是:当应用 initialRoute 时,须要确保你没有同时定义 home 属性。
2、给特定的 route 传参:
1) 定义须要传递的参数
class ScreenArguments {
final String title;
final String message;
ScreenArguments(this.title, this.message);
}
2) 创立组件来获取参数
class ExtractArgumentsScreen extends StatelessWidget {
static const routeName = '/extractArguments';
@override
Widget build(BuildContext context) {final ScreenArguments args = ModalRoute.of(context).settings.arguments;
return Scaffold();}
}
3) 把组件注册到路由表中
MaterialApp(
routes: {ExtractArgumentsScreen.routeName: (context) => ExtractArgumentsScreen(),},
);
4) 导航到组件
RaisedButton(onPressed: () {
Navigator.pushNamed(
context,
ExtractArgumentsScreen.routeName,
arguments: ScreenArguments(
'Extract Arguments Screen',
'This message is extracted in the build method.',
),
);
},
),
5) onGenerateRoute
提取参数
MaterialApp(onGenerateRoute: (settings) {if (settings.name == PassArgumentsScreen.routeName) {
final ScreenArguments args = settings.arguments;
return MaterialPageRoute(builder: (context) {
return PassArgumentsScreen(
title: args.title,
message: args.message,
);
},
);
}
},
);