5
2

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`のルーティング管理パッケージ`go_router`の使い方

Last updated at Posted at 2022-05-15

Flutterのルーティング管理パッケージgo_routerについて以下の内容について記述します。

  • インストール方法
  • 基本的な使い方
  • 応用的な使い方
    • 階層構造を持ったページを作りたい場合
    • ページ遷移時にパラメータを渡したい
    • エラー検知してエラーページを表示したい場合

パッケージのインストール

pubspec.yamldependenciesgo_routerを追加します。

pubspec.yaml
dependencies:
+  go_router:

flutter pub getでインストールします

$ flutter pub get

基本的な使い方

アプリケーションでの初期設定

lib/main.dartでアプリケーションのroutergo_routerを使用するように設定します

main.dart
+ import 'package:go_router/go_router.dart';

class App extends StatelessWidget {
  App({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
+      routerDelegate: _router.routerDelegate,
+      routeInformationParser: _router.routeInformationParser,
+      routeInformationProvider: _router.routeInformationProvider,
    );
  }

+ final _router = GoRouter();
}

具体的な値としてはGoRouter()の中にルーティングを追加していきます。

GoRouter()の書き方

GoRouter()の書き方は以下の通りです。

GoRouter(
  name: 'top',
  path: '/',
  pageBuilder: (context, state) => MaterialPage(
        key: state.pageKey,
        child: Top(),
      ),
)
  • pathにルーティングのパスを書きます
  • nameにルーティングの名前を書きます
    • ルーティングを使用する際にフルパスではなく名前を指定することができるため名前を定義しておくことで呼び出し処理を簡潔にすることができます
  • pageBuilderでページ描画処理を行います
    • 特別な処理を不要な場合childclassを指定するだけです

呼び出し方

ルーティングを呼び出したいclassgo_routerをimportしてcontext.go()またはcontext.goNamed()を使用します。

import 'package:go_router/go_router.dart';

context.go('/');
context.goNamed('top');
  • context.go()を使用する場合はpathで定義したルーティングのパスを引数に指定します
  • context.goNamed()を使用する場合はnameで定義したルーティングの名前を引数に指定します

応用的な使い方

階層構造を持ったページを作りたい場合

以下の画像のように左上に前のページに戻るボタンが設置されるような階層構造を作りたい場合

スクリーンショット 2022-04-24 10.59.42.png

親ページにしたいルーティング定義でroutesに子ページを配列で定義します。

GoRouter(
  name: 'top',
  path: '/',
  pageBuilder: (context, state) => MaterialPage(
        key: state.pageKey,
        child: Top(),
      ),
+  routes: [
+    GoRoute(
+      name: 'users',
+      path: 'users',
+      pageBuilder: (context, state) => MaterialPage(
+        key: state.pageKey,
+        child: Users(),
+    ),
+  ]
)

ページ遷移時にパラメータを渡したい場合

前述の階層構造があるルーティングで親ページから子ページに遷移する際にパラメータを渡したい場合

  1. ルーティングを使う側でextra引数に値を指定します。
context.goNamed('users', extra: 1);
  1. state.extraに値が格納されるのでルーティングの定義の中でchildclassに渡すなど使用します
GoRouter(
  name: 'top',
  path: '/',
  pageBuilder: (context, state) => MaterialPage(
        key: state.pageKey,
        child: Top(),
      ),
  routes: [
    GoRoute(
      name: 'users',
      path: 'users',
      pageBuilder: (context, state) => MaterialPage(
        key: state.pageKey,
        child: Users(
+          user_id: state.extra! as String
        ),
    ),
  ]
)

エラー検知してエラーページを表示したい場合

GoRouter()errorPageBuilderでエラーページの定義をすることで行います。
state.errorにエラーオブジェクトが格納されます。

routes: [
    GoRouter(
      name: 'top',
      path: '/',
      pageBuilder: (context, state) => MaterialPage(
            key: state.pageKey,
            child: Top(),
          ),
],
+  errorPageBuilder: (context, state) => MaterialPage(
+    key: state.pageKey,
+    child: Scaffold(
+      body: Center(
+        child: Text(state.error.toString()),
+      ),
+    ),
+  ),
)

ドキュメント

環境

  • Flutter 2.10.4
  • Dart SDK version: 2.16.2
5
2
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?