Flutter:在聊天屏幕中发送消息时如何用正在进行的对话更新主屏幕?

问题描述 投票:0回答:1

我目前正在开发一个具有聊天功能的 Flutter 应用程序。在我的应用程序中,我有一个主屏幕,显示正在进行的对话列表。每个对话都由与我聊天的人的名字代表。

下面是我的 ChatScreen 和 HomeScreen 小部件:

这是聊天画面

 Expanded(
            child: StreamBuilder<QuerySnapshot>(
              stream:
                  _chatService.getMessage(receiverId, _auth.currentUser!.uid),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return ListView.builder(
                    padding: const EdgeInsets.only(top: 10),
                    reverse: true,
                    itemCount: snapshot.data!.docs.length,
                    itemBuilder: (context, index) {
                      final data = snapshot.data!.docs[index];
                      final userId = data['senderId'];
                      final userMessage = data['message'];
                      final name = data['receiverName'];
                      final timestamp = data['timestamp'] as Timestamp;
                      final DateTime date = timestamp.toDate();
                      final formattedDate = DateFormat.jm().format(date);
                      return Container(
                        margin: userId == _auth.currentUser!.uid
                            ? const EdgeInsets.only(
                                top: 0, bottom: 10, right: 5, left: 70)
                            : const EdgeInsets.only(
                                top: 0, bottom: 10, right: 70, left: 5),
                        child: Column(
                          mainAxisAlignment: userId == _auth.currentUser!.uid
                              ? MainAxisAlignment.end
                              : MainAxisAlignment.start,
                          crossAxisAlignment: userId == _auth.currentUser!.uid
                              ? CrossAxisAlignment.end
                              : CrossAxisAlignment.start,
                          children: [
                            Text(name),
                            Text(formattedDate),
                            Material(
                              color: userId == _auth.currentUser!.uid
                                  ? AppColors.kPrimaryColor
                                  : Colors.black.withOpacity(0.6),
                              borderRadius: userId == _auth.currentUser!.uid
                                  ? const BorderRadius.only(
                                      bottomLeft: Radius.circular(30),
                                      bottomRight: Radius.circular(20),
                                      topLeft: Radius.circular(30),
                                    )
                                  : const BorderRadius.only(
                                      topRight: Radius.circular(30),
                                      bottomLeft: Radius.circular(20),
                                      bottomRight: Radius.circular(30),
                                    ),
                              elevation: 3,
                              child: Padding(
                                padding: userId == _auth.currentUser!.uid
                                    ? const EdgeInsets.only(
                                        left: 20,
                                        right: 15,
                                        top: 10,
                                        bottom: 10)
                                    : const EdgeInsets.only(
                                        left: 15,
                                        right: 20,
                                        top: 10,
                                        bottom: 10),
                                child: Text(
                                  userMessage,
                                  style: const TextStyle(
                                    color: Colors.white,
                                    fontSize: 16,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  );
                }
                return const SizedBox();
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(10.0),
            child: Row(
              children: [
                Expanded(
                  child: MyTextField(
                    controller: _messageController,
                    fillColor: Colors.grey,
                    style: const TextStyle(color: Colors.black, fontSize: 17),
                    keyboardType: TextInputType.multiline,
                    maxLines: null,
                    minLines: 1,
                    filled: true,
                    contentPadding: const EdgeInsets.only(
                        left: 20, right: 20, top: 5, bottom: 5),
                    enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide.none,
                      borderRadius: BorderRadius.circular(30),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide.none,
                      borderRadius: BorderRadius.circular(30),
                    ),
                    hintText: 'Type a message...',
                  ),
                ),
                const SizedBox(width: 5),
                CircleAvatar(
                  // radius: 22,
                  minRadius: 20,
                  backgroundColor: AppColors.kPrimaryColor,
                  child: IconButton(
                    onPressed: () async {
                      if (_messageController.text.isNotEmpty) {
                        await _chatService.addMessage(
                          receiverId,
                          _messageController.text,
                          reciverName,
                        );
                      }

这是主屏幕 如何获取我保存在云 Firestore 中的接收器的 ID。

 StreamBuilder<QuerySnapshot>(
                  stream: _chatService.getMessage(_auth.currentUser!.uid, otherUserId),
                  builder: (context, snapshot) {
                    if (!snapshot.hasData) {
                      return const Center(child: CircularProgressIndicator());
                    }
                    return Flexible(
                      child: ListView.builder(
                        itemCount: snapshot.data!.docs.length,
                        itemBuilder: (context, index) {
                          final data = snapshot.data!.docs[index];

                          final name = data['receiverName'];
                          return Text(name);
                        },
                      ),
                    );
                  })

这是获取消息和时间戳的方法


  Stream<QuerySnapshot> getMessage(String currentUserId, String otherUserId) {
    List<String> ids = [currentUserId, otherUserId];
    ids.sort();
    final roomId = ids.join("_");
    return _firebaseService
        .collection('chat_room')
        .doc(roomId)
        .collection('messages')
        .orderBy('timestamp', descending: true)
        .snapshots();
  }

我期望获取当前用户正在聊天的人的姓名

flutter firebase google-cloud-firestore
1个回答
0
投票

我假设您有要检索名称的用户的 UID。 使用下面的代码来检索用户名

Future<String> getUserName(String uid) async {
try {
    // Access Firestore collection
    DocumentSnapshot userSnapshot =
        await FirebaseFirestore.instance.collection('YOUR_USER_COLLECTION').doc(uid).get();

    // Check if the user exists
    if (userSnapshot.exists) {
    // Retrieve the display name
    return userSnapshot.data()?['displayName'] ?? "No Display Name";
    } else {
    return "User not found";
    }
   } catch (e) {
    print("Error getting user name: $e");
    return "Error";
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.