Home > Blockchain >  How to access field from document in collection
How to access field from document in collection

Time:06-03

I have a collection of chats in my firestore databse. Within the collection is a bunch of documents. And each document is a message. I ma now trying to access each message and some particular fields from the collection, but i am running into issues.

Here is where I get chats:

_getChats(String individualId) async {
    print("in get chats");
    Query q = FirebaseFirestore.instance
        .collection("users")
        .doc(uid)
        .collection('messages')
        .doc(individualId)
        .collection('chats')
        .orderBy("dateTime", descending: true)
        .limit(10);

    setState(() {
      _loadingChats = true;
    });

    QuerySnapshot querySnapshot = await q.get();
    _chats = querySnapshot.docs;

    setState(() {
      _loadingChats = false;
    });
  }

In the above code, I assign the documents to a list. Here I define the list like:

List<DocumentSnapshot> _chats = [];

Finally, I am using a listview to load the chats like so:

Widget _showChats2() {
    return ListView.builder(itemBuilder: (BuildContext context, int index) {
      //Chat chat = _chats[index];
      bool isMe = _chats[index].data["senderId"] == uid;
      return Align(
        alignment: isMe ? Alignment.centerRight
            : Alignment.centerLeft,
        child: Column(
          children: [
            Align(
              alignment: isMe ? Alignment.centerRight
                  : Alignment.centerLeft,
              child: Card(
                color: isMe
                    ? Colors.purpleAccent
                    : Colors.white,
                elevation: 2,
                child: Padding(
                  padding: const EdgeInsets.all(12),
                  child: Text(
                    _chats[index].data["message"],
                    style: TextStyle(
                        color: isMe
                            ? Colors.white
                            : Colors.black
                    ),
                  ),
                ),
              ),
            ),
            Align(
                alignment: isMe
                    ? Alignment.topRight
                    : Alignment.topLeft,
                child: Padding(
                  padding: isMe ? const EdgeInsets.only(
                      right: 12)
                      : const EdgeInsets.only(left: 12),
                  child: MidText(text: DateFormat('kk:mm').format(
                      _chats[index].data["dateTime"])),
                )
            )
          ],
        ),
      );
    });
  }

I get errors above when I try to access the fields of the document using the square brackets[]. I was wondering the right way to access data from document fields in this case

CodePudding user response:

Instead of _chats[index].data["message"]
try _chats[index]['message']

Here are some suggestions

  1. use streambuilder instead of download chats in list
  2. creare stateless widget for message
  3. Also avoid creating long chain of collection and documents, It will put you inside some boundaries.

StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance
            .collection("users")
            .doc(uid)
            .collection('messages')
            .doc(individualId)
            .collection('chats')
            .orderBy("dateTime", descending: true)
            .limit(10)
            .snapshots(),
        builder: (_, snapshot) {
          return ListView.builder(
            itemCount: snapshot.data!.docs.length,
            itemBuilder: (BuildContext context, int index) {
              return Text(snapshot.data!.docs[index]['message']);
            },
          );
        });

Happy Coding :P

  • Related