本文介绍了如何从itemBuilder访问查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我让随机聊天应用程序使用FirestoreAnimatedList(适用于Firestore的FirebaseAnimatedList).

I am make random chat app use FirestoreAnimatedList (FirebaseAnimatedList for Firestore).

如果同一用户发送很多消息,所以我不想只显示一次用户头像,那么同一时间不显示同一用户头像.

I want show user avatar only one time if same user send many message so not have same avatar show many time.

我的解决方案是使用索引检查同一用户是否发送了最后一条消息.

My solution is use index for check if last message send by same user.

所以我需要检查:

if (snapshot[index - 1][‘user’] == user) {
  return true;
}

但是我的snapshotDocumentSnapshot,因此无法调用[index - 1].

But my snapshot is DocumentSnapshot so cannot call [index - 1].

也许我必须从query获取清单?如何访问才能如此调用列表中的indexquery?

Maybe I must get list from query?How to access so can call index on list and query like this?

谢谢!

这里是示例:

body: FirestoreAnimatedList(
        query: firestore.collection('messages').snapshots(),
        itemBuilder: (
          BuildContext context,
          DocumentSnapshot snapshot,
          Animation<double> animation,
          int index,
        ) {
          return FadeTransition(
            opacity: animation,
            child: MessageItem(
              index: index,
              document: snapshot,
              onTap: _removeMessage,
            ),
          );
        },

推荐答案

您可以将用户存储在Map中.

You can just store the users in a Map.

在小部件的class中,您将必须创建一个变量来保存地图:

In your widget's class, you will have to create a variable to hold the map:

final Map<int, dynamic> users = {};

然后,您可以在itemBuilder回调中填充地图:

Then, you can populate the map in the itemBuilder callback:

itemBuilder: (
          BuildContext context,
          DocumentSnapshot snapshot,
          Animation<double> animation,
          int index,
        ) {
          users[index] = snapshot['user']; // added line
          return FadeTransition(
            opacity: animation,
            child: MessageItem(
              index: index,
              document: snapshot,
              onTap: _removeMessage,
            ),
          );
        },

现在,您可以做您想做的事情:

Now, you can do what you wanted:

if (users[index - 1] == user) {
  return true;
}

这篇关于如何从itemBuilder访问查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 00:16