【问题标题】:How can I use the arguments passed with pushNamed?如何使用 pushNamed 传递的参数?
【发布时间】:2019-10-24 18:57:23
【问题描述】:

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

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

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

【问题讨论】:

    标签: flutter dart flutter-navigation


    【解决方案1】:

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

    在/secondRoute 的构建方法中:

    final args = ModalRoute.of(context).settings.arguments as Map<String, String>;
    final arg1 = args["key"];
    

    【讨论】:

      【解决方案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.',
        ),
      );
      

      【讨论】:

      • 在问题的上下文中,这里的firstRoute和secondRoute是什么?
      • 在您的情况下,使用“/secondRoute”而不是ExtractArgumentsScreen.routeName 并向其发送参数。这只是一个如何发送和提取所需参数的示例
      • 非常感谢。它起作用了,被困了好几天了:D
      • 我试过了。但是,它在 ModalRoute.of(context).settings.arguments 中给出错误“getter 'settings' was called on null'”。这段代码有什么问题?
      猜你喜欢
      • 1970-01-01
      • 2020-09-03
      • 2011-10-11
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 2022-08-19
      相关资源
      最近更新 更多