Update UserTileChats to auto-refresh UI on Firebase changes.

master
Rafael 2024-06-18 11:55:06 +02:00
parent 63bedb0280
commit f1c0542e49
2 changed files with 41 additions and 16 deletions

View File

@ -1,3 +1,4 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../models/message.dart'; import '../models/message.dart';
@ -45,7 +46,6 @@ class UserTileChats extends StatelessWidget {
Widget buildProfileIcon() { Widget buildProfileIcon() {
return Row( return Row(
children: [ children: [
// Profile image
if (profileImageUrl != null && profileImageUrl!.isNotEmpty) if (profileImageUrl != null && profileImageUrl!.isNotEmpty)
CircleAvatar( CircleAvatar(
backgroundImage: NetworkImage(profileImageUrl!), backgroundImage: NetworkImage(profileImageUrl!),
@ -53,7 +53,7 @@ class UserTileChats extends StatelessWidget {
), ),
// Icon if profile image is not set // Icon if profile image is not set
if (profileImageUrl == null || profileImageUrl!.isEmpty) if (profileImageUrl == null || profileImageUrl!.isEmpty)
const Icon(Icons.person), const Icon(Icons.person, size: 36),
const SizedBox(width: 12), const SizedBox(width: 12),
], ],
@ -61,13 +61,10 @@ class UserTileChats extends StatelessWidget {
} }
Widget buildMsgContent() { Widget buildMsgContent() {
String msgDateString = '';
String msgContent = '';
bool? outgoing;
String chatRoomID = getCompoundId([currentUserId ?? '', otherUserId ?? '']); String chatRoomID = getCompoundId([currentUserId ?? '', otherUserId ?? '']);
return FutureBuilder<Message?>( return StreamBuilder<Message?>(
future: ChatService().getLastMessage(chatRoomID), stream: ChatService().getLastMessageStream(chatRoomID),
builder: (context, snapshot) { builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) { if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator(); return const CircularProgressIndicator();
@ -82,7 +79,13 @@ class UserTileChats extends StatelessWidget {
return buildMsgDetails('No messages yet', '', null); return buildMsgDetails('No messages yet', '', null);
} else { } else {
Message lastMessage = snapshot.data!; Message lastMessage = snapshot.data!;
msgDateString = formatTimestamp(lastMessage.timestamp); String msgDateString = '';
String msgContent = '';
bool? outgoing;
if (lastMessage.timestamp !=
Timestamp.fromMillisecondsSinceEpoch(0)) {
msgDateString = formatTimestamp(lastMessage.timestamp);
}
if (lastMessage.senderID == currentUserId) { if (lastMessage.senderID == currentUserId) {
msgContent = 'Me: ${lastMessage.message}'; msgContent = 'Me: ${lastMessage.message}';

View File

@ -58,6 +58,24 @@ class ChatService {
await batch.commit(); await batch.commit();
} }
/// Retrieves a stream of the last message of a chatroom.
Stream<Message?> getLastMessageStream(String chatRoomID) {
return _firestore
.collection(Constants.dbCollectionChatRooms)
.doc(chatRoomID)
.collection(Constants.dbCollectionMessages)
.orderBy(Constants.dbFieldMessageTimestamp, descending: true)
.limit(1)
.snapshots()
.map((snapshot) {
if (snapshot.docs.isEmpty) {
return null;
}
var lastMessageDoc = snapshot.docs.first;
return Message.fromMap(lastMessageDoc.data());
});
}
/// Retrieves the last message of a chatroom. /// Retrieves the last message of a chatroom.
/// ///
/// Returns [null] in case of an error. /// Returns [null] in case of an error.
@ -77,16 +95,20 @@ class ChatService {
.limit(1) .limit(1)
.get(); .get();
DocumentSnapshot lastMessageDoc = messageSnapshot.docs.first; if(messageSnapshot.docs.isNotEmpty) {
if (lastMessageDoc.exists) { DocumentSnapshot lastMessageDoc = messageSnapshot.docs.first;
senderID = lastMessageDoc[Constants.dbFieldMessageSenderId]; if (lastMessageDoc.exists) {
senderEmail = lastMessageDoc[Constants.dbFieldMessageSenderEmail]; senderID = lastMessageDoc[Constants.dbFieldMessageSenderId];
receiverID = lastMessageDoc[Constants.dbFieldMessageReceiverId]; senderEmail = lastMessageDoc[Constants.dbFieldMessageSenderEmail];
message = lastMessageDoc[Constants.dbFieldMessageText]; receiverID = lastMessageDoc[Constants.dbFieldMessageReceiverId];
timestamp = lastMessageDoc[Constants.dbFieldMessageTimestamp]; message = lastMessageDoc[Constants.dbFieldMessageText];
timestamp = lastMessageDoc[Constants.dbFieldMessageTimestamp];
}
} else {
debugPrint('Info: getLastMessage -> messageSnapshot is EMPTY');
} }
} catch (e) { } catch (e) {
debugPrint('DebugPrint: getLastMessage -> ${e.toString()}'); debugPrint('Error on getLastMessage: ${e.toString()}');
return null; return null;
} }