1
0

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 1 year has passed since last update.

【学習メモ:Flutter入門編】 go_routerの使い方

Posted at

これから「Flutter」を勉強していこうと思っている人向けには「メモ」程度で参照してみてください。

■ go_router(ゴールーター)とは?
昔から使われていた「navogator」の仕組みが、時代の移り変わりで利用しにくくなってきたので、新しく「navogator 2.0」が提供されたが、仕様(仕組み)が複雑のため、その機能を使いやすくするため(補完するため)に提供されているパッケージ。

■ 「go_router」の使い方
「パス」と「画面」の組み合わせを決める(定義する)だけなようです。

■ 「go_router」使うための定義
「pubspec.yaml」に以下の定義を追加する必要がある。

dependencies:
+ go_router:
  flutter_riverpod:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.6

保存するとVSCodeが、自動的に必要なパッケージをダウンロードしてくれる模様。

■ アプリ全体を作成する際のポイント
「StatelessWidget」をひな形を作成した際に付与されている「const」の定義は、「go_router」では一緒に利用する事ができないので、記載を削除しておく必要がある。

class MainApp extends StatelessWidget {
- const MainApp({super.key});
+ MainApp({super.key});

「go_router」による画面遷移を利用するために必要な定義を以下のように定義しておく必要がある。

@override
Widget build(BuildContext context) {
  // ここから
+ return MaterialApp.router(
+   routeInformationProvider: router.routeInformationProvider,
+   routeInformationParser: router.routeInformationParser,
+   routerDelegate: router.routerDelegate,
+ );
  // ここまでが「go_router」の決まった書き方となる。
}

画面の繊維は「go_router」の機能で用意されている「push()」と「pop()」を呼び出すことで簡単に画面遷移が可能となる。

なお「go()」という関数を利用する事で、直接指定したパスに遷移する事もできるようだ。

【定義例】

// 指定した画面に移動(進む)
push(BuildContext context) {
  context.push('/b');
}

// 一つ前の画面に移動(戻る)
back(BuildContext context) {
  context.pop();
}

// 指定した画面に移動(ジャンプ)
move(BuildContext context) {
  context.go('/c');
}

■ 「BuildContext」について
基本的には「Flutter」が自動で作成してくれるものであり、余り詳しく学習する必要は現時点ではないらしい。

最後に

Flutter(Dart言語)に関する最低限の情報を「学習メモ」としてまとめてみました。
内容に誤りがありそうであれば、遠慮なくご指摘いただけますと幸いです。

【学習の参考にした動画】
素敵な解説動画の作成ありがとうございます。
本記事の内容より。動画を見た方が解りやすいと思います。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?