首页 > 解决方案 > 编写此飞镖迭代并返回列表的更好方法是什么

问题描述

目的是进行某种连接。从 firestore 中的用户文档中获取每个用户文档,并通过 uid 将其附加到某个集合中。然后返回包含用户文档完整详细信息的集合,而不仅仅是 uid。

Future<List<ChatRoom>> getChatsrooms(uid) async {
    ChatRoom chatroom = new ChatRoom();
    try {
      List<ChatRoom> chatrooms = new List();
      var snapshots = await _db
          .collection('my-chats-chats')
          .where('users', arrayContains: uid)
          .orderBy('updated_at', descending: true)
          .get();

      for (var room in snapshots.docs) {
        chatroom.chatroomid = room.data()['chatroomid'];
        chatroom.users = room.data()['users'];
      
        // get user profile that isn'nt u.
        List<dynamic> userids = await room.data()['users']
          ..remove(uid);

        var doc = await _db.collection('my-chats-users').doc(userids[0]).get();

        UserModel user = UserModel.fromMap(doc.data());

        chatroom.users.add(user);

        // Remove the users string UID from users list
        chatroom.users.remove(user.uid);
        chatroom.users.remove(uid);

        chatrooms.add(chatroom);

      }

      return chatrooms.toList();
 
    } catch (e) {
      print("Couldn't get user\'s chatrooms exception: " + e.toString());
      return null;
    }
  }

上面似乎做了我想要的,除了返回的聊天室列表,只包含一个聊天室的重复项。因此,即使有 10 个不同的聊天室,我也只会重复一个聊天室 10 次。

我在想的是chatrooms.add(chatroom);唯一添加的一项。但是聊天室列表应该是一个可增长的列表。那么为什么最终只有一个重复的项目呢?

写这个更好的方法是什么?

标签: flutterdart

解决方案


推荐阅读