简体   繁体   中英

Get stream of results from Firebase Realtime Database inside nested array inside nested document in Flutter

I am currently developing a chatting page on my mobile application and was using Realtime Database to reduce costs. Not having much Realtime Database experience, I am running into issues developing a page for active chatrooms where each user has a document with their uid where there is an array of chats . How can I generate a list of the first names based on the items inside of the array of chats .

在此处输入图像描述

I realize it's best practice to show code you have tried, however, I have only used Firebase Firestore and have no idea where to start, considering the complexity of the structure

You can try this answer. Here I have created StreamBuilder for getting data once. As I have provided, Stream outside of StreamBuilder means it will create a stream only once.

final _snap = FirebaseDatabase.instance
      .ref()
      .child(`users/${uid}`)

StreamBuilder<Event>(
  stream: _snap.onValue,
  builder: (BuildContext context, snapshot) {
    if (snapshot.hasData) {
      DataSnapshot snap = snapshot.data as DataSnapshot;
      List<dynamic> chatArray = snap.value['chats'];
      List<String> firstNames = [];
      for (var chat in chatArray) {
        String firstName = chat[recepientFirstName];
        firstNames.add(firstName);
      }
      return ListView.builder(
        itemCount: firstNames.length,
        itemBuilder: (context, index) {
          return Text(firstNames[index]);
        },
      );
    } else {
      return Text('Loading...');
    }
  },
)

Found similar reference about this Questions so you can also visit these threads:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM