在Flutter-Listview

问题描述

我正在尝试通过Flutterfirebase-firestore显示实时聊天屏幕(等于whatsapp的主屏幕)。

工作:创建所有“对等”联系人列表。看看我的Listview:

Container(
  child: StreamBuilder(
    stream:
        //FirebaseFirestore.instance.collection('users').snapshots(),FirebaseFirestore.instance
            .collection('users')
            .doc(currentUserId)
            .collection('peers')
            .snapshots(),builder: (context,snapshot) {
      if (!snapshot.hasData) {
        return Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysstoppedAnimation<Color>(themeColor),),);
      } else {
        return ListView.builder(
          padding: EdgeInsets.all(10.0),itemBuilder: (context,index) =>
              buildItem(context,snapshot.data.documents[index]),itemCount: snapshot.data.documents.length,);
      }
    },

不起作用:为每个图块加载特定数据,例如最后一条消息名称。在创建第一个列表时,我无法查询此信息(第一个查询返回对等ID,第二个查询返回对等ID的userdata)。我的buildItem方法由另一个streambuilder组成,但是,当第一个streambuilder进行更改时,应用程序将冻结。

  Widget buildItem(BuildContext context,DocumentSnapshot document) {
      return StreamBuilder<DocumentSnapshot>(
        stream: FirebaseFirestore.instance
            .collection('users')
            .doc(document.data()['peerId'])
            .snapshots(),builder: ...

这是嵌套流的正确方法吗?简单的Listviews记录得很好,但是我在Google上找不到很好的例子。任何帮助表示赞赏。

解决方法

尝试在initState中仅创建一次流,并将其传递给此方法:

//in initState
peersStream = FirebaseFirestore.instance
            .collection('users')
            .doc(currentUserId)
            .collection('peers')
            .snapshots(),

然后在stream: peersStream中使用StreamBuilder

此外,建议在小部件的方法上使用小部件类:https://stackoverflow.com/a/53234826/5066615