GoRouterはpathでは無くnameパラメータによって画面遷移させる事もできます。
列挙型でルート名を定義・管理することができるのでpathを引数として渡す遷移より管理がしやすいです。
呼び出す際に、pathによる場合は文字列リテラルを渡しますが、名前付きルートではハードコーディングする必要が無くなります。よって自動入力の提案を受ける事が出来るようになり入力ミスを減らせます。
【実装フロー】
①定義
- enum AppRoute {
- home,
- detail,
- }
- final GoRouter _router = GoRouter(
- routes: <RouteBase>[
- GoRoute(
- path: '/',
- name: AppRoute.home.name,
- builder: (BuildContext context, GoRouterState state) {
- return const HomeScreen();
- },
- routes: <RouteBase>[
- GoRoute(
- path: 'details',
- name: AppRoute.detail.name,
- builder: (BuildContext context, GoRouterState state) {
- return const DetailsScreen();
- },
- ),
- ],
- ),
- ],
- );
②nameを使用して遷移 goNamed
- ElevatedButton(
- onPressed: () => context.goNamed(AppRoute.detail.name),
- child: const Text('Go to the Details screen'),
- ),
- ElevatedButton(
- onPressed: () => context.goNamed(AppRoute.home.name),
- child: const Text('Go back to the Home screen'),
- ),
参考資料