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

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

【Flutter】GoRouter 名前付きルート

GoRouterはpathでは無くnameパラメータによって画面遷移させる事もできます。

列挙型でルート名を定義・管理することができるのでpathを引数として渡す遷移より管理がしやすいです。

呼び出す際に、pathによる場合は文字列リテラルを渡しますが、名前付きルートではハードコーディングする必要が無くなります。よって自動入力の提案を受ける事が出来るようになり入力ミスを減らせます。

 

【実装フロー】

①定義

  1. enum AppRoute {
  2.   home,
  3.   detail,
  4. }
  5.  
  6. final GoRouter _router = GoRouter(
  7.   routes: <RouteBase>[
  8.     GoRoute(
  9.       path: '/',
  10.       name: AppRoute.home.name,
  11.       builder: (BuildContext context, GoRouterState state) {
  12.         return const HomeScreen();
  13.       },
  14.       routes: <RouteBase>[
  15.         GoRoute(
  16.           path: 'details',
  17.           name: AppRoute.detail.name,
  18.           builder: (BuildContext context, GoRouterState state) {
  19.             return const DetailsScreen();
  20.           },
  21.         ),
  22.       ],
  23.     ),
  24.   ],
  25. );

 

②nameを使用して遷移 goNamed

  1. ElevatedButton(
  2.           onPressed: () => context.goNamed(AppRoute.detail.name),
  3.           child: const Text('Go to the Details screen'),
  4.         ),

 

  1. ElevatedButton(
  2.           onPressed: () => context.goNamed(AppRoute.home.name),
  3.           child: const Text('Go back to the Home screen'),
  4.         ),

 

参考資料

pub.dev