前回、Flutterの環境構築をしたので今度はそのプロジェクトに対して一般的なプロジェクトに必要そうなプラグイン(package)を入れつつ、軽く実装していく
今回は、頻出であるgo_router(クライアントサイドルーティング)、flutter hooks(state管理)(に本当に少しだけ触れる)について触れる
導入するパッケージ
go_router
クライアントサイドルーティングを容易にしてくれるパッケージ 公式
下記コマンドでinstall
flutter pub add go_router
hooks_riverpod(or flutter_riverpod)
flutter開発では、グローバルな状態管理としてriverpodがよく採用されており(ミニマルなアプリなら入れる必要は無いが、そこそこの規模なら欲しい)、
そのriverpod公式が「ローカルな状態管理ではhooksを使うべき」と言ってます
参考
というわけで、riverpodとhooksがセットになっているhooks_riverpodを今回は入れることにします
flutter pub add hooks_riverpod
なお、後の記事でriverpod側(globalな状態保持)については触れる予定です
今回は、hooksの一部だけ触っていきます(localな状態保持)
導入したプラグインを使用してデフォルトアプリをUpdateしていく
オリジナルのソース
前回の環境構築記事で記載した flutter new projectにて新規プロジェクトを作成した場合、lib配下にはmain.dartのみ存在しているはず。内容は下記の通り
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
上記1ソースだったものを適宜分割しつつ、GoRouterのルーティング設定や、遷移先のページなども作成していく
なお、プロジェクト内のlib配下のフォルダ構成は下記のようになっている
...\GITHUB\FLUTTER_APPLICATION_INITIAL_SET\LIB
│ main.dart
│ my_app.dart
│
├─feature
│ ├─my_home_page
│ │ └─view
│ │ my_home_page.dart
│ │
│ └─second_page
│ └─view
│ second_page.dart
│
└─router
router.dart
(my_app.dartの位置は微妙だが) エントリポイントとなるmain.dartはlib直下に、それ以外の各画面は feature
フォルダ配下に配置
共通的なコンポーネント等はlib/component、多言語関連等は lib/i18n 等のように配置していこうと考えている
遷移元、遷移先のページを作成していく
main.dartに MyHomePage Widgetを定義している部分があるが、その部分をまるっと切り出して、
lib/feature/my_home_page/view
配下にmy_home_page.dart として作成
この時点で、flutter hooksによるlocalなstate管理をさせるためのコードへの変更も一緒に行ってしまう
import 'package:flutter/material.dart';
import 'package:flutter_application_1/router/router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class MyHomePage extends HookConsumerWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
Widget build(BuildContext context, WidgetRef ref) {
var _counter = useState(0);
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'${_counter.value}',
style: Theme.of(context).textTheme.headlineMedium,
),
ElevatedButton(
onPressed: () {
context.push('/second_page');
},
child: const Text('Move2NextPage'),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => _counter.value++,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
オリジナルのソースでは、 createState
し、下記のように内部状態と値をコントロールするメソッドを定義していたところを、
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
下記のように useState
とする。これでstateの宣言をしつつ、以降_counterの変更を直接行うことが可能になる()
var _counter = useState(0);
counterの値を変更している箇所が、オリジナルだとこうだが、
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
hooksを使うとこうなる。値の参照時は、_counter.value となる
floatingActionButton: FloatingActionButton(
onPressed: () => _counter.value++,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
それ以外に、画面遷移を実現させるために、画面遷移用のボタンを新たに配置
ElevatedButton(
onPressed: () {
context.push('/second_page');
},
child: const Text('Move2NextPage'),
),
go_routerによる画面遷移は、context.push 等で遷移可能。
import 'package:go_router/go_router.dart';
のように、ちゃんとgo_routerをimportしていないと、context.pushが使えないので注意
context.pushだと画面をスタックし、context.goはスタックさせずに(スタックを消して)画面遷移します
context.popは、現在表示されている画面をスタックから削除して前画面に戻ります
次は、遷移先画面の方を作成していきます
lib/feature/second_page/view
配下に、second_view.dart ファイルを作成、下記のようにコーディングする
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
class SecondPage extends HookConsumerWidget {
const SecondPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
appBar: AppBar(),
body: const Column(
children: [
Text('This is SecondPage!!'),
],
),
);
}
}
こちらはとてもシンプルで、画面上に「This is SecondPage!!」と表示するだけのページ
ルーティング用のファイルを作成する
import 'package:flutter_application_1/feature/my_home_page/view/my_home_page.dart';
import 'package:flutter_application_1/feature/second_page/view/second_page.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
final goRouterProvider = Provider<GoRouter>((ref) {
return GoRouter(
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) =>
const MyHomePage(title: 'My Home Page!!'),
routes: <RouteBase>[
GoRoute(
path: 'second_page',
builder: (context, state) => const SecondPage(),
)
]),
],
);
});
このあたりはGoRouterのお決まりの定義方法です
ルートパスにMyHomePageを紐づけ、 /second_page にSecondPageを紐づけしています
main.dartをupdate
最後に、main.dartを下記のように修正する
main.dartがモリモリだったものを適宜分割
import 'package:flutter/material.dart';
import 'package:flutter_application_1/my_app.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
runApp(
const ProviderScope(
child: MyApp(),
),
);
}
mainは枠のみを記述することとし、描画するコンポーネントやそれらのルーティングは別ファイルに任せることとする
Riverpod公式の通りにProviderScopeをrunAppに渡すように設定
次に、main.dartから追い出したMyAppに関する記述を下記のように行う
import 'package:flutter/material.dart';
import 'package:flutter_application_1/feature/my_home_page/view/my_home_page.dart';
import 'package:flutter_application_1/router/router.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class MyApp extends ConsumerWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context, WidgetRef ref) {
final goRouter = ref.watch(goRouterProvider);
return MaterialApp.router(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
routerConfig: goRouter,
);
}
}
もともとのmain.dartの一部をコピペしたのに加え、先ほど作成したGoRouterに関する記述も追加している
return MaterialApp(
だった部分を return MateriaApp.router(
に変更、
goRouterProviderをrouterConfigとして設定するように修正を加えている
あまりにもショボいが、一旦はここまで。
ソースは下記に配置。
https://github.com/hidepy/flutter_application_initial_set/tree/feature/qiita01-source