假设我有两条路线/firstRoute和/secondRoute,分别用于小部件FirstRoute和SecondRoute。我正在使用一些参数将命名路由推入堆栈,就像这样......
Navigator.pushNamed(
context,
"/secondRoute",
arguments: <String, String>{"key" : "value"},
)
我现在如何在SecondRoute中使用这个值?查看了文档,但没有提及。
假设我有两条路线/firstRoute和/secondRoute,分别用于小部件FirstRoute和SecondRoute。我正在使用一些参数将命名路由推入堆栈,就像这样......
Navigator.pushNamed(
context,
"/secondRoute",
arguments: <String, String>{"key" : "value"},
)
我现在如何在SecondRoute中使用这个值?查看了文档,但没有提及。
利用ModalRoute.of(context).settings.arguments
在您的构建方法中/secondRoute
:
final args = ModalRoute.of(context).settings.arguments as Map<String, String>;
final arg1 = args["key"];
为参数创建类:
class ScreenArguments {
final String title;
final String message;
ScreenArguments(this.title, this.message);
}
并在小部件中提取它们:
class ExtractArgumentsScreen extends StatelessWidget {
static const routeName = '/extractArguments';
@override
Widget build(BuildContext context) {
// Extract the arguments from the current ModalRoute settings and cast
// them as ScreenArguments.
final ScreenArguments args = ModalRoute.of(context).settings.arguments;
return Scaffold(
appBar: AppBar(
title: Text(args.title),
),
body: Center(
child: Text(args.message),
),
);
}
}
对于发送参数:
Navigator.pushNamed(
context,
ExtractArgumentsScreen.routeName,
arguments: ScreenArguments(
'Extract Arguments Screen',
'This message is extracted in the build method.',
),
);