首页 > 解决方案 > 从多个数据库节点填充 Flutter ListView

问题描述

我正在尝试使用来自我的 Firebase 实时数据库实例的多个节点的数据填充 ListView.builder。

我对监听节点上的更改(并在它们发生时更新列表视图)感兴趣,但对节点chats上的实时更新不太感兴趣。chats-details

chats
-- 'chat1' 
---- 'keyA' : 'This is some text'
---- 'keyB' : 'This is some text'

-- 'chat2' 
---- 'keyA' : 'This is some text'
---- 'keyB' : 'This is some text'

chats-details
-- 'chat1' 
---- 'keyC' : 'This is some text'
---- 'keyD' : 'This is some text'

-- 'chat2' 
---- 'keyC' : 'This is some text'
---- 'keyD' : 'This is some text'

理想情况下,chat1、chat2...等的所有数据都将附加到 Object(myChats在下面的示例中)并输入 ListView。

任何帮助将不胜感激。我当前的代码如下。此代码当前不会自动填充 ListView。

  // Node 1 - Listen to changes
  chatsRef = FirebaseDatabase().reference().child('chats');

  // Node 2 - Update when node 1 is updated
  chatsDetailsRef = FirebaseDatabase().reference().child('chats-details');

  @override
  Widget build(BuildContext context) {
    List<Chats> myChats = [];

    return Scaffold(
        appBar: AppBar(),
        body: StreamBuilder(
          stream: chatsRef.onValue,
          builder: (context, snap) {

            if (snap.hasData && !snap.hasError && snap.data.snapshot.value != null) {
              Map data = snap.data.snapshot.value;

              data.forEach((index, data) {
                chatsDetailsRef.child(index).once().then((DataSnapshot snapshot) {

                  Chats currentChat = Chats.fromMap(data);

                  if (snapshot.value == null) {
                    Chat emptyChatDetails = Chat();
                    currentChat.chatDetails = emptyChatDetails;
                  } else {
                    Chat foundChatDetails = ChatDetails.fromMap(snapshot.value);
                    currentChat.chatDetails = foundChatDetails;
                  }

                  myChats.add(currentChat);

                });


              });
              return ListView.builder(
                itemCount: myChats.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(myChats[index].title),
                    subtitle: Text(myChats[index].chatDetails.detail),
                  );
                },
              );
            } else {
              return Center(child: Text("No data"));
            }
          },
        ),
    );
  }
}

标签: firebaseflutterfirebase-realtime-database

解决方案


每当您将项目添加到 myChats 时,您是否尝试过调用 setState?

setState(() {
    myChats.add(currentChat);
});

https://api.flutter.dev/flutter/widgets/State/setState.html

此外,您当前myChats每次运行构建函数时都重新定义数组,这意味着只要重新构建小部件,它将清除其中的所有聊天。如果您希望保留这些聊天,则必须将该数组声明为该类本身的成员


推荐阅读