Fix: Handle getLastMessage when no message exists

master
Rafael 2024-06-06 18:45:23 +02:00
parent 25b76e6274
commit 6d776874c7
2 changed files with 77 additions and 62 deletions

View File

@ -72,12 +72,14 @@ class UserTileChats extends StatelessWidget {
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text(
'Error: ${snapshot.error}',
return Expanded(
child: Text(
'Error <last message>: ${snapshot.error}',
style: const TextStyle(color: Colors.red),
),
);
} else if (!snapshot.hasData || snapshot.data == null) {
return const Text('No messages yet');
return buildMsgDetails('No messages yet', '', null);
} else {
Message lastMessage = snapshot.data!;
msgDateString = formatTimestamp(lastMessage.timestamp);
@ -90,6 +92,14 @@ class UserTileChats extends StatelessWidget {
outgoing = false;
}
return buildMsgDetails(msgContent, msgDateString, outgoing);
}
},
);
}
Widget buildMsgDetails(
String msgContent, String msgDateString, bool? outgoing) {
return Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@ -133,7 +143,4 @@ class UserTileChats extends StatelessWidget {
),
);
}
},
);
}
}

View File

@ -1,5 +1,6 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/foundation.dart' show debugPrint;
import '../../constants.dart';
import '../../utils/helper.dart';
@ -58,13 +59,16 @@ class ChatService {
}
/// Retrieves the last message of a chatroom.
Future<Message> getLastMessage(String chatRoomID) async {
///
/// Returns [null] in case of an error.
Future<Message?> getLastMessage(String chatRoomID) async {
String senderID = '';
String senderEmail = '';
String receiverID = '';
String message = '';
Timestamp timestamp = Timestamp.fromDate(DateTime.utc(1970, 01, 01));
Timestamp timestamp = Timestamp.fromMillisecondsSinceEpoch(0);
try {
QuerySnapshot messageSnapshot = await _firestore
.collection(Constants.dbCollectionChatRooms)
.doc(chatRoomID)
@ -81,6 +85,10 @@ class ChatService {
message = lastMessageDoc[Constants.dbFieldMessageText];
timestamp = lastMessageDoc[Constants.dbFieldMessageTimestamp];
}
} catch (e) {
debugPrint(e.toString());
return null;
}
return Message(
senderID: senderID,