Home > Blockchain >  How can I get data from various nodes in a Realtime-database in Flutter?
How can I get data from various nodes in a Realtime-database in Flutter?

Time:06-16

I'm trying to display data from a real-time database in my widget, such as a picture, a name, or a message, but I'm not sure how to achieve it from several nodes. Thank you in advance for your assistance.

For add data :

List lists = [];

stream to get data :

 final dbRef = FirebaseDatabase.instance
  .ref()
  .child("chatList")
  .child("D1NilPUI6PY0jSA1tk0wRzi6FsO2");

Widget to show data :

_widget() {
    return StreamBuilder(
      stream: dbRef.onValue,
      builder: (BuildContext context, AsyncSnapshot snap) {
        if (snap.hasData &&
            !snap.hasError &&
            snap.data!.snapshot.value != null) {
          Map data = snap.data.snapshot.value;
          List item = [];

          data.forEach((index, data) => item.add({"chatList": index, ...data}));
          print("DATA : $item");

          if (snap.connectionState == ConnectionState.waiting) {
            return const CircularProgressIndicator();
          } else {
            return ListView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: item.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(item[index]['content'].toString()),
                );
              },
            );
          }
        } else {
          return const Center(child: Text("No data"));
        }
      },
    );
  }

Table structure Images :

Image 1 : enter image description here

Image 2 : enter image description here

CodePudding user response:

This code:

final dbRef = FirebaseDatabase.instance
  .ref()
  .child("chatList")
  .child("D1NilPUI6PY0jSA1tk0wRzi6FsO2");

This refers to a node /chatList/D1NilPUI6PY0jSA1tk0wRzi6FsO2 in your database. Since the screenshot doesn't show any data under that exact path, you will get a snapshot without any value from reading it.

If you want to read all nodes under /chatList, you can use that path in the query, and then loop over all the children of the snapshot.

final dbRef = FirebaseDatabase.instance
  .ref()
  .child("chatList");
dbRef.onValue.listen((event) => {
  event.snapshot.children.forEach((child) {
    print(child.key);
  })
})

Since you have two levels with dynamic keys under chatList, you'll have to use two nested loops to get to the named properties:

final dbRef = FirebaseDatabase.instance
  .ref()
  .child("chatList");
dbRef.onValue.listen((event) => {
  event.snapshot.children.forEach((child) {
    print(child.key);
    child.children.forEach((child2) {
      print(child2.key);
      print(child2.child("lastMessage/content").value);
    })
  })
})
  • Related