1

假设我有两条路线/firstRoute/secondRoute,分别用于小部件FirstRouteSecondRoute。我正在使用一些参数将命名路由推入堆栈,就像这样......

Navigator.pushNamed(
    context,
    "/secondRoute",
    arguments: <String, String>{"key" : "value"},
)

我现在如何在SecondRoute中使用这个值?查看了文档,但没有提及。

4

2 回答 2

6

利用ModalRoute.of(context).settings.arguments

在您的构建方法中/secondRoute

final args = ModalRoute.of(context).settings.arguments as Map<String, String>;
final arg1 = args["key"];
于 2019-10-25T01:02:07.563 回答
2

为参数创建类:

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.',
  ),
);
于 2019-10-24T19:07:49.927 回答