1
3

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 3 years have passed since last update.

Flutter(Dart)でRealtimeDatabaseを使う

Last updated at Posted at 2021-03-27

はじめに

最近、バージョン2にアップグレードされたFlutterで遊んでいます
そこで、RealtimeDatabaseで躓いたので、メモ代わりにおいておきます

FireStore使えばいいじゃん

Firebase+Flutterでデータベースを扱う場合、FireStoreかRealtimeDatabaseになるわけなのですが
Qiitaの記事を見ても新しいFireStoreばっかりでRealtimeDatabaseに関する記事が少ないです。。。
しかし、FireStoreの読み取り回数の無料枠の低さたるや、、、
FireStoreだと直ぐに無料枠超えるので、RealtimeDatabaseを使いたい!ってことです

どんなデータ?

下記のようなデータが入っているデータベースからデータを取り出す
image.png

set(Insert)、updateは別に躓かなかったので今回は書かない

実際のコード

sample.dart
//ここまではFireStoreと同じ
var ref = FirebaseDatabase.instance.reference();

//onceはFireStoreでいうところの、get();
Future<DataSnapshot> products = ref.child('product/').once();

List<dynamic> productList = [];
//prodcutの子要素は配列なのでMap<dynamic, dynamic>に変換してforeachする
(snapshot.data.value as Map<dynamic, dynamic>).forEach((key, value) {
   //RealtimeDatabaseから取り出したデータは、Jsonではない何かなので、Jsonに変換する
   var json = new Map<String, dynamic>.from(products.value[key]);
   //リストに突っ込む
   productList.add(json);
});

参考文献

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?