確認環境
$ flutter --version
Flutter 3.3.4 • channel stable • https://github.com/flutter/flutter.git
Framework • revision eb6d86ee27 (3 weeks ago) • 2022-10-04 22:31:45 -0700
Engine • revision c08d7d5efc
Tools • Dart 2.18.2 • DevTools 2.15.0
Riverpodのインストール
pubspec.yaml
dependencies:
flutter:
sdk: flutter
flutter_hooks: ^0.18.5+1
hooks_riverpod: ^2.0.2
...
StateProvider を使う
StateProviderとは
StateProvider は外部から変更が可能なステート(状態)を公開するプロバイダです。
サンプルコード
右下の +
ボタンを押すと、カウントアップされるアプリケーション。
lib/main.dart
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
void main() {
runApp(ProviderScope(child: MyApp()));
}
final counterProvider = StateProvider((ref) => 1);
class MyApp extends ConsumerWidget {
// This widget is the root of your application.
Widget build(BuildContext context, WidgetRef ref) {
var counter = ref.watch(counterProvider.notifier);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('My First app'),
),
body: Text('count: ${ref.watch(counterProvider)}'),
floatingActionButton: FloatingActionButton(
onPressed: () => {counter.update((state) => state + 2)},
child: const Icon(Icons.add),
),
),
);
}
}