(Async)NotifierProviderと(Async)Notifierは、ユーザーの操作に反応して変化する状態を管理するためのRiverpodの推奨ソリューションである。
これは、通常、次のような目的で使用されます。
カスタムイベントに反応した後、時間の経過とともに変化する可能性のある状態を公開する。
状態を変更するためのロジック(別名「ビジネスロジック」)を一箇所に集中させ、長期的な保守性を向上させる。
使用例として、Todo-Listを実装するためにNotifierProviderを使用することができます。そうすることで、addTodoのようなメソッドを公開し、ユーザーインタラクションでUIがTodoのリストを変更できるようにします。
使用するユースケース
使い方は、StateNotifierとそれほど変わらない気がします。このように書くことができます。
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_template/about_state_notifire/note_app/note_model/notes_model.dart';
class NoteNotifier extends Notifier<List<NotesModel>> {
// 初期値を作る.
List<NotesModel> build() {
return [];
}
// 空っぽのクラスに、id、フォームの値、現在時刻を保存する.
void addNote(NotesModel note) {
state = [...state, note];
}
// ダミーのデータを削除する.
void removeNote(NotesModel note) {
state = state.where((_note) => _note != note).toList();
}
}
しかし、もっと楽に作る方法があるとしたらどうします?
Riverpod2.0からは、ジェネレーターなるものが登場しました。慣れたら難しくないかと思いましたが、まだまだ未知のものなので、使うのは躊躇しますね。
どんなものかというと、Notifierクラスを呼び出すプロバイダーを自動生成してくれるところですね。
やり方
pubspec.yamlにジェネレーターを使うのに必要なパッケージを追加する。
name: flutter_template
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1
environment:
sdk: '>=2.18.6 <3.0.0'
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
flutter_riverpod: ^2.2.0
riverpod_annotation: ^1.1.1 # riverpod_generatorに必要なパッケージ.
json_annotation: ^4.7.0 # Freezedに必要なパッケージ.
freezed_annotation: ^2.2.0 # Freezedに必要なパッケージ.
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^2.0.0
json_serializable: ^6.5.4 # Freezedに必要なパッケージ.
freezed: ^2.3.2 # Freezedに必要なパッケージ.
build_runner: ^2.3.3 # riverpod_generatorに必要なパッケージ.
riverpod_generator: ^1.1.1 # riverpod_generatorに必要なパッケージ.
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
モデルクラスを定義する
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/foundation.dart';
part 'notes_model.freezed.dart';
part 'notes_model.g.dart';
class NotesModel with _$NotesModel {
const factory NotesModel({
required int id,
required String body,
required DateTime createdAt,
}) = _NotesModel;
factory NotesModel.fromJson(Map<String, dynamic> json) =>
_$NotesModelFromJson(json);
}
コマンドを実行する
dart pub run build_runner watch
で、本題のジェネレーターなんですけど、お作法があるみたいで、ファイルを作ったら決まったコードを書いてコマンドを実行します。
import 'package:riverpod_annotation/riverpod_annotation.dart'; // このコードを書く
part 'note_provider.g.dart'; // note_providerのところは、ファイル名と同じにする.
// @riverpodのアノテーションをつける
class NoteApp extends _$NoteApp {
List<NotesModel> build() => [];
// 空っぽのクラスに、id、フォームの値、現在時刻を保存する.
void addNote(NotesModel note) {
state = [...state, note];
}
// ダミーのデータを削除する.
void removeNote(NotesModel note) {
state = state.where((_note) => _note != note).toList();
}
}
ファイルを自動生成するコマンドを実行する
dart pub run build_runner watch
プロバイダーファイルが自動生成されると使用できるようになる。モデルクラスをインポートすれば、出ていたエラーは全て消えるはずです。
import 'package:flutter_template/about_state_notifire/note_app/note_model/notes_model.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart'; // このコードを書く
part 'note_provider.g.dart'; // note_providerのところは、ファイル名と同じにする.
class NoteApp extends _$NoteApp {
List<NotesModel> build() => [];
// 空っぽのクラスに、id、フォームの値、現在時刻を保存する.
void addNote(NotesModel note) {
state = [...state, note];
}
// ダミーのデータを削除する.
void removeNote(NotesModel note) {
state = state.where((_note) => _note != note).toList();
}
}
プロバイダーが書いてあるファイルが自動生成されました。これは、ref.watchで読み込むことができます。
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'note_provider.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// ignore_for_file: avoid_private_typedef_functions, non_constant_identifier_names, subtype_of_sealed_class, invalid_use_of_internal_member, unused_element, constant_identifier_names, unnecessary_raw_strings, library_private_types_in_public_api
/// Copied from Dart SDK
class _SystemHash {
_SystemHash._();
static int combine(int hash, int value) {
// ignore: parameter_assignments
hash = 0x1fffffff & (hash + value);
// ignore: parameter_assignments
hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10));
return hash ^ (hash >> 6);
}
static int finish(int hash) {
// ignore: parameter_assignments
hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3));
// ignore: parameter_assignments
hash = hash ^ (hash >> 11);
return 0x1fffffff & (hash + ((0x00003fff & hash) << 15));
}
}
String _$NoteAppHash() => r'eac6db245985afce08acc697df0a53317281aec3';
/// See also [NoteApp].
final noteAppProvider = AutoDisposeNotifierProvider<NoteApp, List<NotesModel>>(
NoteApp.new,
name: r'noteAppProvider',
debugGetCreateSourceHash:
const bool.fromEnvironment('dart.vm.product') ? null : _$NoteAppHash,
);
typedef NoteAppRef = AutoDisposeNotifierProviderRef<List<NotesModel>>;
abstract class _$NoteApp extends AutoDisposeNotifier<List<NotesModel>> {
List<NotesModel> build();
}
アプリを使う画面
StateNotifierのコードを少し書き換えて使ってるだけです。自動生成されたプロバイダーを呼び出して、状態を持っているメソッドを使ってダミーのデータを追加、削除ができます。
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_template/about_state_notifire/note_app/note_generater/note_provider.dart';
import 'package:flutter_template/about_state_notifire/note_app/note_model/notes_model.dart';
import 'package:flutter_template/about_state_notifire/note_app/note_state/notes_statet.dart';
// StateNotifierクラスを外部ファイルで呼び出すプロバイダー.
final noteProvider = StateNotifierProvider<NoteNotifier, List<NotesModel>>(
(ref) => NoteNotifier());
class NoteGeneratePage extends ConsumerWidget {
const NoteGeneratePage({
Key? key,
}) : super(key: key);
Widget build(BuildContext context, WidgetRef ref) {
// ref.watchで、初期値が空のリストを呼び出して、監視する。
final noteAppGenerater = ref.watch(noteAppProvider);
// 入力フォームの値をリストに保存するTextEditingController.
final bodyController = TextEditingController();
// ランダムな数値を作り出す変数.
final randomId = Random().nextInt(100) + 50;
// 現在時刻を表取得する変数.
DateTime createdAt = DateTime.now();
return Scaffold(
appBar: AppBar(
title: const Text('Notes Generate'),
),
body: SingleChildScrollView(
child: Center(
child: Column(
children: [
const SizedBox(height: 40),
Container(
width: 300,
child: TextField(
controller: bodyController,
decoration: InputDecoration(
labelText: 'Content',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
// NoteModelクラスに、ダミーのデータを引数として渡して保存する.
ref.read(noteAppProvider.notifier).addNote(NotesModel(
id: randomId,
body: bodyController.text,
createdAt: createdAt));
},
child: const Text('Add note')),
const SizedBox(height: 20),
noteAppGenerater.isEmpty
? const Text('Add notes ')
: ListView.builder(
itemCount: noteAppGenerater
.length, // StateNotifierのリストに追加されたデータの数を数える.
shrinkWrap: true,
itemBuilder: (context, index) {
final note = noteAppGenerater[index];
return ListTile(
title: Text(
'id: ${note.id} memo: ${note.body}'), // idとフォームから入力された値を表示.
subtitle: Text(note.createdAt
.toIso8601String()), // リストにデータを追加した時刻を表示.
trailing: IconButton(
icon: const Icon(Icons.delete),
onPressed: () {
// リストのidを取得してボタンを押したリストだけ削除する.
ref
.read(noteAppProvider.notifier)
.removeNote(noteAppGenerater[index]);
},
),
);
})
],
),
),
));
}
}
アプリを実行するコード
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_template/about_state_notifire/note_app/ui/notes_generate.dart';
import 'package:flutter_template/about_state_notifire/note_app/ui/notes_page.dart';
void main() {
runApp(ProviderScope(child: const MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
appBarTheme: const AppBarTheme(
backgroundColor: Colors.indigoAccent, // AppBarの色.
foregroundColor: Colors.grey, // AppBarのフォントの色.
centerTitle: true, // AppBarのAndroidのタイトルを中央寄せにする.
)),
home: const NoteGeneratePage(),
);
}
}
StateNotifierと同じように動作しています。公式のページでもジェネレーター使っているので、これからはやるかもしれないですね🤔