【问题标题】:Flutter Firestore How to list people I only have chat history with?Flutter Firestore 如何列出我只有聊天记录的人?
【发布时间】:2021-06-21 07:15:53
【问题描述】:

这是我的聊天主页的一部分,它列出了我的 firestore 数据库中的每个用户。但我想让它列出我唯一联系过的人。

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

我的 Firestore 数据路径的图片,例如:

Users collection

Messages collection

An example message doc

Tried:

set({friends array}) for per user in google sign in auth function 但每次我登录时它都会重置该数组,因此没有必要更新该数组,因为它会在每次用户登录时重置好友/联系人列表。

【问题讨论】:

    标签: android firebase flutter dart google-cloud-firestore


    【解决方案1】:

    首先你需要存储好友信息,你可以添加一个简单的if check after google sign in auth function,如果一个文档存在就不要创建一个新的文档来解决你的重置问题。

    假设您有一个带有 firestore 文档 ID 的 currentUser 对象

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

    获取当前用户的好友列表,可以通过映射将其转换为用户id列表。

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

    【讨论】:

    • link 这是我在登录页面中如何保存用户数据的查询。如何添加一个简单的 if 来检查该文档中是否有“朋友”数组?
    • .where("id",whereIn: friendsIds) 是我应该为每个用户创建的 Firestore 用户文档中的 FriendsIds 数组,它保留联系人的 ID?
    • final userDoc = await db.collection("users").doc(uid).get() if(userDoc.exists == false) { // friendsIds 下面的代码是 ' 的映射版本朋友的数组你基本上可以说一些像这样的朋友.map( (data) => data.id ).toList()
    猜你喜欢
    • 2021-08-08
    • 2018-08-31
    • 2021-08-25
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    相关资源
    最近更新 更多