アプリ開発・ゲーム開発のための勉強ブログ

FlutterとUnrealEngineの勉強をしています。

【Flutter】GoRouterで画面遷移を行う 実装フロー

pub.dev

Navigator 1・2に代わる簡易的な画面遷移のプラグインとして登場したのがGoRouterです。

GoRouterはコンストラクタで指定するルート(Route)の集合体によって全体が制御され、管理されています。

また、ディープリンクやその他の一般的な画面遷移をすべて使いやすい API でサポートしています。

 

【実装フロー】

①パッケージを追加

pub.dev

 

②MaterialAppをMaterialApp.routerに変更

  1. class MyApp extends StatelessWidget {
  2.   const MyApp({super.key});
  3.  
  4.   @override
  5.   Widget build(BuildContext context) {
  6.     return MaterialApp.router(
  7.       routerConfig: _router,
  8.     );
  9.   }
  10. }

 

GoRouterの宣言(ルーティングの宣言・定義)

  1. final GoRouter _router = GoRouter(
  2.   routes: <RouteBase>[
  3.     GoRoute(
  4.       path: '/',
  5.       builder: (BuildContext context, GoRouterState state) {
  6.         return const HomeScreen();
  7.       },
  8.       // ↓を ネストにしてサブルート化
  9.       routes: <RouteBase>[
  10.         GoRoute(
  11.           path: 'details',
  12.           builder: (BuildContext context, GoRouterState state) {
  13.             return const DetailsScreen();
  14.           },
  15.         ),
  16.       ],
  17.     ),
  18.   ],
  19. );
  • グローバル変数としてGoRouter()オブジェクトを宣言する
  • routes:プロパティの中でルーティングを作る →pathと遷移先のスクリーンウィジェットを変えたルートを作るだけ
  • 最初のルートパスは '/'
  • name:プロパティも設定できる(ルート名を入れる)
  • ネストしてサブルートにしないと戻ることができなくなるので注意
  • 最初にinitialLocationやdebugLogDiagonosticsプロパティを設定することもある

 

④ルートを呼び出す(ページ遷移)

  1. ElevatedButton(
  2.           onPressed: () => context.go('/details'),
  3.           child: const Text('Go to the Details screen'),

 

  1. ElevatedButton(
  2.           onPressed: () => context.go('/'),
  3.           child: const Text('Go back to the Home screen'),
  4.         ),
  • ボタンのonPressed等から呼び出す
  • GoRouter.of(context).go('パス')を省略したのがcontext.go('パス')
  • パスの代わりにname(ルート名)で呼び出す方が簡単

 

名前付きルートで呼び出す方法↓

 

【おまけ】

ページスライドの挙動を変えるpageBuilderプロパティ GoRouter内で定義

GoRoute(
  path: 'details',
  pageBuilder: (context, state) {
    return CustomTransitionPage(
      key: state.pageKey,
      child: DetailsScreen(),
      transitionsBuilder: (context, animation, secondaryAnimation, child) {
        // Change the opacity of the screen using a Curve based on the the animation's
        // value
        return FadeTransition(
          opacity:
              CurveTween(curve: Curves.easeInOutCirc).animate(animation),
          child: child,
        );
      },
    );
  },
),

docs.page


 

 

 

参考資料はこちら

 

 

blog.pentagon.tokyo