简体   繁体   English

Flutter Firestore 如何列出我只有聊天记录的人?

[英]Flutter Firestore How to list people I only have chat history with?

This is a part of my chat homepage & it lists every user in my firestore database.这是我的聊天主页的一部分,它列出了我的 firestore 数据库中的每个用户。 But I want to make it list the only people I contacted with.但我想让它列出我唯一接触过的人。

Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        backgroundColor: Colors.white,
        title: Text(
          'Sohbet',
          style: TextStyle(color: primaryColor, fontWeight: FontWeight.bold),
        ),
        iconTheme: IconThemeData(
          color: Colors.black, //change your color here
        ),
        centerTitle: true,
        actions: <Widget>[
          PopupMenuButton<Choice>(
            onSelected: onItemMenuPress,
            itemBuilder: (BuildContext context) {
              return choices.map((Choice choice) {
                return PopupMenuItem<Choice>(
                    value: choice,
                    child: Row(
                      children: <Widget>[
                        Icon(
                          choice.icon,
                          color: primaryColor,
                        ),
                        Container(
                          width: 10.0,
                        ),
                        Text(
                          choice.title,
                          style: TextStyle(color: primaryColor),
                        ),
                      ],
                    ));
              }).toList();
            },
          ),
        ],
      ),
      body: WillPopScope(
        child: Stack(
          children: <Widget>[
            // List
            Container(
              child: StreamBuilder(
                stream: FirebaseFirestore.instance
                    .collection('users')
                    .limit(_limit)
                    .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,
                      controller: listScrollController,
                    );
                  }
                },
              ),
            ),

            // Loading
            Positioned(
              child: isLoading ? const Loading() : Container(),
            )
          ],
        ),
      ),
    );
  }

  Widget buildItem(BuildContext context, DocumentSnapshot document) {
    if (document.data()['id'] == _auth.currentUser.uid) {
      return Container();
    } else {
      return Container(
        child: FlatButton(
          child: Row(
            children: <Widget>[
              Material(
                child: document.data()['photoUrl'] != null
                    ? CachedNetworkImage(
                        placeholder: (context, url) => Container(
                          child: CircularProgressIndicator(
                            strokeWidth: 1.0,
                            valueColor:
                                AlwaysStoppedAnimation<Color>(themeColor),
                          ),
                          width: 50.0,
                          height: 50.0,
                          padding: EdgeInsets.all(15.0),
                        ),
                        imageUrl: document.data()['photoUrl'],
                        width: 50.0,
                        height: 50.0,
                        fit: BoxFit.cover,
                      )
                    : Icon(
                        Icons.account_circle,
                        size: 50.0,
                        color: greyColor,
                      ),
                borderRadius: BorderRadius.all(Radius.circular(25.0)),
                clipBehavior: Clip.hardEdge,
              ),
              Flexible(
                child: Container(
                  child: Column(
                    children: <Widget>[
                      Container(
                        child: Text(
                          '${document.data()['nickname']}',
                          style: TextStyle(color: primaryColor),
                        ),
                        alignment: Alignment.centerLeft,
                        margin: EdgeInsets.fromLTRB(10.0, 0.0, 0.0, 5.0),
                      ),
                      /*Container(
                        child: Text(
                          'About me: ${document.data()['aboutMe'] ?? 'Not available'}',
                          style: TextStyle(color: primaryColor),
                        ),
                        alignment: Alignment.centerLeft,
                        margin: EdgeInsets.fromLTRB(10.0, 0.0, 0.0, 0.0),
                      )*/
                    ],
                  ),
                  margin: EdgeInsets.only(left: 20.0),
                ),
              ),
            ],
          ),
          onPressed: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => Chat(
                          peerId: document.id,
                          peerAvatar: document.data()['photoUrl'],
                        )));
          },
          color: greyColor2,
          padding: EdgeInsets.fromLTRB(25.0, 10.0, 25.0, 10.0),
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
        ),
        margin: EdgeInsets.only(bottom: 10.0, left: 5.0, right: 5.0),
      );
    }
  }

Pics of my firestore data paths like:我的 Firestore 数据路径的图片,例如:

Users collection用户集合

Messages collection消息集合

An example message doc示例消息文档

Tried:

set({friends array}) for per user in google sign in auth function but everytime I sign in it resets that array so there is no point updating that array because it resets that friends/contacts list everytime user signs in. set({friends array}) for per user in google sign in auth function 但每次我登录时它都会重置该数组,因此没有必要更新该数组,因为它会在每次用户登录时重置好友/联系人列表。

First you need to store the friends information, you can add a simple if check after google sign in auth function that if a document exists do not create a new document that would solve your resetting problem.首先,您需要存储朋友信息,您可以在google登录auth function后添加一个简单的if检查,如果文档存在,请不要创建新文档来解决您的重置问题。

Assuming you have a currentUser object with firestore document id's假设您有一个带有 firestore 文档 ID 的 currentUser object

final friends = (await FirebaseFirestore.instance.collection("users").doc(currentUser.id).get()).data;

Get the friends list for the current user, you can convert it to list of user ids by mapping.获取当前用户的好友列表,可以通过映射将其转换为用户id列表。

stream: FirebaseFirestore.instance
                .collection('users')
                .where("id",whereIn: friendsIds)
                .limit(_limit)
                .snapshots(),

i know this is super late but it might be useful for future search.我知道这已经很晚了,但它可能对未来的搜索有用。 in every chat room(in your case it is messages), you need to create a field members which has a type of array or map.在每个聊天室(在您的情况下是消息)中,您需要创建一个具有数组类型或 map 的字段members Inside that array, you need to store your id and the id of the person you are chatting with.在该数组中,您需要存储您的 id 和与您聊天的人的 id。 After that, you can just query the chat rooms .where((room) => room.members.contains(//your_id)) .之后,您可以查询聊天室.where((room) => room.members.contains(//your_id))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM