LoginSignup
1

More than 1 year has passed since last update.

[Flutter] [Navigator] 次画面へ複数の値を渡す方法

Posted at

Navigatorによる画面遷移時に次画面へ値を渡す方法です。
SQLiteやSharedPreferencesで保持する必要はなく、ライトに値を渡したいときにご参考になればと思います。

渡したい値が1つの場合

変数 hogeを次画面に渡す例

第3引数のargumentsに変数 hoge をセットします。

遷移元


String hoge = 'hoge';
Navigator.pushReplacementNamed(
  context,
  '/next_path',
  arguments: hoge
);

遷移先


final String hoge = ModalRoute.of(context).settings.arguments;

渡したい値が複数ある場合

変数 hogeId, fuga を次画面に渡す例

渡したい値をまとめたクラスを作成し、そのオブジェクトを渡します。
名前はなんでも良いので、ViewAToBArguments というクラス名で以下のように作成するとします。

ViewAToBArguments.dart

class ViewAToBArguments {
  final int hogeId;
  final String fuga;

  ViewAToBArguments(this.hogeId, this.fuga);
}

第3引数のargumentsに ViewAToBArguments オブジェクトをセットします。

遷移元


int hogeId = 1;
String fuga = 'fuga';
Navigator.pushReplacementNamed(
  context,
  '/next_path',
  arguments: ViewAToBArguments(hogeId, fuga)
);

遷移先


final ViewAToBArguments viewAToBArguments = ModalRoute.of(context).settings.arguments;
int hogeId = viewAToBArguments.hogeId;
String fuga = viewAToBArguments.fuga;

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
What you can do with signing up
1