メインコンテンツに進む

はじめに


オンラインで Riverpod を試す

Riverpod の感覚を掴むために、Dartpad で試してみましょう。

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

インストールするパッケージが決まったら、次のものを pubspec.yaml に追記してください:

pubspec.yaml
name: my_app_name
environment:
sdk: ">=2.17.0 <3.0.0"
flutter: ">=3.0.0"

dependencies:
flutter:
sdk: flutter
flutter_riverpod: ^2.1.3
riverpod_annotation: ^1.1.1

dev_dependencies:
build_runner:
riverpod_generator: ^1.1.1

そして flutter pub get でパッケージをインストールしてください。

最後に、 でコードジェネレータを実行してください。flutter pub run build_runner watch

これで Riverpod がアプリに追加されました!

使用例: Hello world

Riverpod がインストールできたので、これを使うことができます。

以下のスニペットは新しい依存性を使って "Hello World" を表示する例です。

lib/main.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'main.g.dart';

// We create a "provider", which will store a value (here "Hello world").
// By using a provider, this allows us to mock/override the value exposed.

String helloWorld(HelloWorldRef ref) {
return 'Hello world';
}

void main() {
runApp(
// For widgets to be able to read providers, we need to wrap the entire
// application in a "ProviderScope" widget.
// This is where the state of our providers will be stored.
ProviderScope(
child: MyApp(),
),
);
}

// Extend ConsumerWidget instead of StatelessWidget, which is exposed by Riverpod
class MyApp extends ConsumerWidget {

Widget build(BuildContext context, WidgetRef ref) {
final String value = ref.watch(helloWorldProvider);

return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Example')),
body: Center(
child: Text(value),
),
),
);
}
}

そして flutter run を実行してください。
実行すると、デバイスに "Hello World" が表示されます。

一歩先へ: コードスニペットのインストール

FlutterVS Code を使っている場合、 Flutter Riverpod Snippets が利用できます。

FlutterAndroid Studio もしくは IntelliJ を使っている場合、 Flutter Riverpod Snippets が利用できます。

img

次のステップ

基本的なコンセプトを学ぶ:

使用例を学ぶ: