1
1

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.

RiverpodのStreamProviderを使用してRealtimeDatabaseから値を取得

Posted at

概要

RiverpodのStreamProviderによってRealtimeDatabaseを監視し、変更があれば即座に画面に反映する。

模擬店システムに使用した例:
模擬店システム.gif

手順

1. StreamProviderのインスタンスを作成

import 'package:firebase_database/firebase_database.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

final myDataProvider = StreamProvider<DatabaseEvent>((ref) async* {
    yield* FirebaseDatabase.instance
          .ref("/* 取得したいデータのパスを指定 */")
          .onValue;
});

2. HookConsumerWidgetを継承したクラスを宣言

class MyPage extends HookConsumerWidget {
  const MyPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Container();
  }
}

3. ref.watch()を使用してProviderからAsyncValueを取得

@override
Widget build(BuildContext context, WidgetRef ref) {
  //変更を監視
  final myDataAsyncVal = ref.watch(myDataProvider);

  return Container();
}

4. asyncVal変数.when()を返り値に割り当てる

@override
Widget build(BuildContext context, WidgetRef ref) {
    //変更を監視
    final myDataAsyncVal = ref.watch(myDataProvider);
    
    return myDataAsyncVal.when(
        loading: () => const CircularProgressIndicator(), //ロード時の処理
        error: (error, stackTrace) => Text(error.toString()), //エラー時の処理
        data: (event) { //正常に取得できた時の処理
          return Container();
        }
    );
}

5. 仮引数eventを使用してDBからデータを取得

@override
Widget build(BuildContext context, WidgetRef ref) {
//変更を監視
final myDataAsyncVal = ref.watch(myDataProvider);

return myDataAsyncVal.when(
    loading: () => const CircularProgressIndicator(), //ロード時の処理
    error: (error, stackTrace) => Text(error.toString()), //エラー時の処理
    data: (event) { //正常に取得できた時の処理
      //ここは取得したいデータの型によって対応を変える
      final String myData = event.snapshot.value.toString();
      return Text(myData);
    }
);
}

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?