LoginSignup
10

More than 3 years have passed since last update.

[Flutter]popUntilメソッドで初期画面に遷移させる

Posted at

はじめに

Flutterで画面遷移させる方法には2種類あります。
1.事前に定義したルートに遷移(Navigator.pushNamed)
2.事前に定義せずに遷移(Navigator.push)

どちらも一つ前の画面に戻るときは Navigator.pop ですが、初期画面(ルートページ)に戻る方法が異なるため、方法をまとめます。

スクリーンショット 2020-05-16 17.08.15.png

1.pushNamedを使っている場合

例えば初期画面に /home と名付けている場合、以下の記述で初期画面に戻ることができます。初期画面ではなく途中で止めたい場合も、同様にwithNameの引数にすることで実現できます。


Navigator.popUntil(context, ModalRoute.withName("/home"));

2.pushを使っている場合

上と比べると少し複雑ですが、下記コードで名前を指定していなくとも初期画面まで戻ることができます。


Navigator.popUntil(context, (Route<dynamic> route) => route.isFirst);

また、以下の書き方でも同じことが実現できます。


Navigator.of(context).popUntil((route) => route.isFirst);

参考

■公式ドキュメント
https://flutter.dev/docs/cookbook/navigation/navigation-basics
https://flutter.dev/docs/cookbook/navigation/named-routes
https://api.flutter.dev/flutter/widgets/Navigator/popUntil.html
■stack overflow
https://stackoverflow.com/questions/49672706/flutter-navigation-pop-to-index-1/51562273

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
10