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.

【Flutter】pushNamedの画面遷移にアニメーションをつける方法

Last updated at Posted at 2022-05-26

はじめに

自分のプロジェクト内で、pushNamedで画面遷移をする際の遷移の仕方(アニメーション)を設定したかったんですが、
通常のNavigator.pushと違い、少しめんどくさく、調べてみてもあんまり説明等が充実していなかったので書きます。
注)この記事はflutterよわよわの私が言っていることで、方法はこれだけではないと思うので、あくまで参考程度にしてください!

そんなやり方しなくてももっといい方法あるよ!

とか

ここはこうしたほうがいいよ!

などのあれば教えていただけると嬉しいです。

まず一般的なNavigator.pushを使ったアニメーションの実装の仕方が知りたい方

こちらに一般的な画面遷移について詳しく書いてあるのでご覧ください↓

自分が今回使う方法で画面遷移のアニメーションをつける方法では一般的なNavigator.pushでの画面遷移でも簡単に実装できるようになる方法だと思っているので、よければ最後まで見ていってくれると嬉しいです。

pushNamedを使った画面遷移でのアニメーション実装

ステップ1

page_transitionというパッケージを使う
https://pub.dev/packages/page_transition/install
こちらからインストールしてあげてください。

ステップ2

main.dartのルーティングの設定のところをいじっていきます。

main.dart
routes: <String, WidgetBuilder> {
      '/1': (BuildContext context) => page1(),
      '/2': (BuildContext context) => page2(),
      '/3': (BuildContext context) => page3(),
    },

    //ここにアニメーションをつけて画面遷移をさせたい遷移先のページのパスを設定する
    // 今回の場合はpage4()というページに画面遷移させるという想定で処理を書いていきます。
    onGenerateRoute: (settings) {
        switch (settings.name) {
          case '/4_animation':  //遷移先のページのパスを指定
            return PageTransition(
              child: page4(),  //遷移先のページ指定
              duration: Duration(milliseconds: 150), //遷移スピード
              reverseDuration: Duration(milliseconds: 150), //帰ってくる際の遷移スピード
              type: PageTransitionType.bottomToTop, //遷移のアニメーションの仕方(今回は下から上)
              settings: settings,
            );
          default:
            return null;
        }
      },

    home: page1(),

コードの内容としては'/4_animation'というパスのケースではアニメーションの設定がしてあるPageTransitionを返すようにしています。
1番大事なアニメーションの仕方の指定はtype:で指定でき、今回は下から上の画面遷移(bottomToTop)にしています。遷移のtypeについては
fade
rightToLeft
leftToRight
topToBottom
bottomToTop
scale (with alignment)
rotate (with alignment)
size (with alignment)
rightToLeftWithFade,
leftToRightWithFade,
leftToRightJoined,
rightToLeftJoined,

があります。詳しくはこちらをみてみてください。

ステップ3

画面遷移の処理を書く

animation_example.dart
Navigator.pushNamed(
              context, 
              '/4_animation', //遷移したいページのパスを指定する
             // argumentsで次の画面に値を渡す場合
              arguments: Arguments(...),
            );

これでアニメーションをつけて画面遷移することができるようになります!
参考になれば幸いです。

最後に

pushNamedの画面遷移だけじゃなくて、一般的なpushでも簡単にアニメーションを実装することができるのでぜひ使ってみてください

今回使用したパッケージ
https://pub.dev/packages/page_transition

参考にした記事等↓
https://stackoverflow.com/questions/53670706/flutter-navigator-pushnamed-custom-route-animation

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?