Home > Enterprise >  Flutter how to get value from firebase and show in streambuilder list
Flutter how to get value from firebase and show in streambuilder list

Time:11-25

I am trying to display 'title' in a list view in flutter but it doesn't work.

enter image description here

I am using this code:

StreamBuilder(
                  stream: Firestore.instance
                      .collection(widget.user.uid)
                      .orderBy('date', descending: true)
                      .snapshots(),
                  builder: (BuildContext context,
                      AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (!snapshot.hasData) {
                      return Center(
                        child: CircularProgressIndicator(),
                      );
                    }

                    return ListView(
                      children: snapshot.data.documents.map((document) {
                        return Center(
                          child: Container(
                            width: MediaQuery.of(context).size.width / 1.2,
                            height: MediaQuery.of(context).size.height / 6,
                            child: Text("Title: "   document['title']),
                          ),
                        );
                      }).toList(),
                    );
                  }),

'activities' is an array, that contains maps with string 'title'. What can I do to solve this?

CodePudding user response:

I re-written the StreamBuilder code, I see that you're using an older version of Firebase SDK for Flutter, check https://firebase.flutter.dev/ for new migrations, and updates on the SDK.

Try, this code:

return StreamBuilder(
      stream: FirebaseFirestore.instance
          .collection(widget.user.uid)
          .orderBy('date', descending: true)
          .snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }

        if (snapshot.hasData) {
          return ListView(
            children: snapshot.data!.docs.map((document) {
              final current = document.data() as Map<String, dynamic>;
              final activities = current["activities"] as List;
              List titles = activities.map((e) => e["title"]).toList();

              return Center(
                child: Container(
                  width: MediaQuery.of(context).size.width / 1.2,
                  height: MediaQuery.of(context).size.height / 6,
                  child: Text("Title: $titles"),
                ),
              );
            }).toList(),
          );
        }

        return const Text("no data");
      },
    );
  • Related