0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Navigator.pushNamedで渡された値をコンストラクタの引数として使いたいとき

Last updated at Posted at 2021-08-09

まず前提として、

Navigator.pushNamed(context, "/page", arguments: "渡したい引数");

こんな感じでpushNamedに引数を渡せますよね。
そして次は受け取る方法です。

でよく紹介されているのは

Widget build(BuildContext context) {
    final args = ModalRoute.of(context)!.settings.arguments;
    print(args) // "渡したい引数"
    ...
}

こういうやつですよね。

でもこれだとcontextが必要なので、buildの中にしか書けません。
ちょっと不便です。
そこでこちら。

MaterialApp(
  ...
  onGenerateRoute: (settings) {
    if (settings.name == "/page") {
      // ↓settings.argumentsに渡された引数入ってる
      final args = settings.arguments as ScreenArguments;
      return MaterialPageRoute(
        builder: (context) {
          // ↓こんな感じで引数をコンストラクタに渡せるので便利
          return NextPage(
            // args = "渡したい引数"
            title: args,
          );
        },
      );
    }
    assert(false, 'Need to implement ${settings.name}');
    return null;
  },
)

この方法だと、NextPageのコンストラクタに自分で引数を渡せるので、自由度が高くて便利です。

公式HPから引用。
https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?