Flutter路由传参总体来说有两种方式,一种是通过构造函数传参,一种是通过路由参数传参。这两种方式都可以使用自定义的PageRoute或者路由名来进行导航;
- PageRoute传入路由参数
// 使用PageRoute传入路由参数
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ExtractArgumentsScreen(),
settings: RouteSettings(
arguments: ScreenArguments(
'Extract Arguments Screen',
'This message is extracted in the build method.',
),
),
),
);
- 使用路由名加路由参数
// 使用路由名导航
Navigator.pushNamed(
context,
ExtractArgumentsScreen.routeName,
arguments: ScreenArguments(
'Extract Arguments Screen',
'This message is extracted in the build method.',
),
);
- 构造函数传参
// 使用路由构造函数传参
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return PassArgumentsScreen(
title: args.title,
message: args.message,
);
},
),
);
- 路由传参转构造传参
// 如果一个路由只有构造传参方式,但想通过路由参数传参,可以通过在MaterialApp中onGenerateRoute拦截后改写成构造传参
MaterialApp(
// ignore: missing_return
onGenerateRoute: (settings) {
if (settings.name == PassArgumentsScreen.routeName) {
final ScreenArguments args = settings.arguments;
return MaterialPageRoute(
builder: (context) {
return PassArgumentsScreen(
title: args.title,
message: args.message,
);
},
);
}
},
);
...
Navigator.pushNamed(
context,
PassArgumentsScreen.routeName,
arguments: ScreenArguments(
'Accept Arguments Screen',
'This message is extracted in the onGenerateRoute function.',
),
);