Navigator 1・2に代わる簡易的な画面遷移のプラグインとして登場したのがGoRouterです。
GoRouterはコンストラクタで指定するルート(Route)の集合体によって全体が制御され、管理されています。
また、ディープリンクやその他の一般的な画面遷移をすべて使いやすい API でサポートしています。
【実装フロー】
①パッケージを追加
②MaterialAppをMaterialApp.routerに変更
- class MyApp extends StatelessWidget {
- const MyApp({super.key});
- @override
- Widget build(BuildContext context) {
- return MaterialApp.router(
- routerConfig: _router,
- );
- }
- }
③GoRouterの宣言(ルーティングの宣言・定義)
- final GoRouter _router = GoRouter(
- routes: <RouteBase>[
- GoRoute(
- path: '/',
- builder: (BuildContext context, GoRouterState state) {
- return const HomeScreen();
- },
- // ↓を ネストにしてサブルート化
- routes: <RouteBase>[
- GoRoute(
- path: 'details',
- builder: (BuildContext context, GoRouterState state) {
- return const DetailsScreen();
- },
- ),
- ],
- ),
- ],
- );
- グローバル変数としてGoRouter()オブジェクトを宣言する
- routes:プロパティの中でルーティングを作る →pathと遷移先のスクリーンウィジェットを変えたルートを作るだけ
- 最初のルートパスは '/'
- name:プロパティも設定できる(ルート名を入れる)
- ネストしてサブルートにしないと戻ることができなくなるので注意
- 最初にinitialLocationやdebugLogDiagonosticsプロパティを設定することもある
④ルートを呼び出す(ページ遷移)
- ElevatedButton(
- onPressed: () => context.go('/details'),
- child: const Text('Go to the Details screen'),
- ElevatedButton(
- onPressed: () => context.go('/'),
- child: const Text('Go back to the Home screen'),
- ),
- ボタンの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,
);
},
);
},
),
参考資料はこちら