LoginSignup
30
24

More than 5 years have passed since last update.

FlutterのStreamBuilderでFirestoreに保存されているデータを表示する

Posted at

StreamBuilderのイメージ

まず、StreamBuilderの和訳はStreamは「流れる」、Builderは「建築者」なので「流れる建築者」という意味です。
これじゃあよくわからないですね。。

StreamBuilderのイメージは、コードの順序関係なく流れてきたデータをキャッチして処理を行う感じです。

そして2つの要素、streamとbuilderから構成されています。
では、次にコードをもとに詳細を説明します。

コード全体

main.dart
        Widget userName() {

    return StreamBuilder<QuerySnapshot>(

        //表示したいFiresotreの保存先を指定
        stream: Firestore.instance
        .collection('users')
        .document(firebaseUser.uid)
        .collection("transaction")
        .snapshots(),

        //streamが更新されるたびに呼ばれる
        builder: (BuildContext context,
            AsyncSnapshot<QuerySnapshot> snapshot) {

          //データが取れていない時の処理
          if (!snapshot.hasData) return const Text('Loading...');

          return Text(snapshot.data.documents[0]['userName']);

        }
     );
  }

表示したい場所にuserName()を記載すれば使える。

stream部分解説

main.dart
stream: Firestore.instance
        .collection('users')
        .document(firebaseUser.uid)
        .collection("transaction")
        .snapshots(),

streamでは表示したいFirestoreの保存先を指定します。そして最後に、【.snapshots()】を記載してデータを取得します。

builder部分解説

main.dart
 //streamが更新されるたびに呼ばれる
 builder: (BuildContext context,
            AsyncSnapshot<QuerySnapshot> snapshot) {

          //データが取れていない時の処理
          if (!snapshot.hasData) return const Text('Loading...');

          return Text(snapshot.data.documents[0]['userName']);

        }

builderはstreamが更新するするたびに呼ばれます。

【AsyncSnapshot<QuerySnapshot> snapshot】

一番上のこの部分で先程snapshotsで取得したデータをsnapshotに代入しています。

【if (!snapshot.hasData) return const Text('Loading...');】

この部分は、snapshotにデータが代入できていないときLoading... と表示する処理です。

【return Text(snapshot.data.documents[0]['userName']);】

最後にこの部分でデータを表示させています。
documents[0]の部分で表示させたいデータのindex番号を指定しています。['userName']で表示したいフィールド名を指定しています。

30
24
1

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
30
24