如何使用通过 pushNamed 传递的参数?
How can I use the arguments passed with pushNamed?
假设我有两条路线 /firstRoute 和 /secondRoute,都用于小部件 FirstRoute 和 SecondRoute。我将带有一些参数的命名路由推入堆栈,就像这样...
Navigator.pushNamed(
context,
"/secondRoute",
arguments: <String, String>{"key" : "value"},
)
现在如何在 SecondRoute 中使用此值?
查看了文档,但没有提及。
为参数创建 class:
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.',
),
);
使用ModalRoute.of(context).settings.arguments
在 /secondRoute
的构建方法中:
final args = ModalRoute.of(context).settings.arguments as Map<String, String>;
final arg1 = args["key"];
假设我有两条路线 /firstRoute 和 /secondRoute,都用于小部件 FirstRoute 和 SecondRoute。我将带有一些参数的命名路由推入堆栈,就像这样...
Navigator.pushNamed(
context,
"/secondRoute",
arguments: <String, String>{"key" : "value"},
)
现在如何在 SecondRoute 中使用此值? 查看了文档,但没有提及。
为参数创建 class:
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.',
),
);
使用ModalRoute.of(context).settings.arguments
在 /secondRoute
的构建方法中:
final args = ModalRoute.of(context).settings.arguments as Map<String, String>;
final arg1 = args["key"];