How to access query from itemBuilder?

江枫思渺然 提交于 2020-01-06 08:33:20

问题


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.

So I need check like :

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

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

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

Thanks!

Here example:

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,
            ),
          );
        },

回答1:


You can just store the users in a Map.

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

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

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;
}


来源:https://stackoverflow.com/questions/55199281/how-to-access-query-from-itembuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!