I’m developing a Flutter application where I need to display the last seen status of a user in the chat page. I’m retrieving the user’s last seen timestamp from Firestore and attempting to format it for display in the app’s AppBar. However, I’m encountering issues with converting the Firestore Timestamp to a DateTime object and subsequently formatting it correctly.
chat page code
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class ChatPage extends StatelessWidget {
static const String screenRoute = "ChatPage";
@override
Widget build(BuildContext context) {
final args = ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;
final name = args['name'];
final ImageLink = args['ImageLink'];
final lastSeenTimestamp = args['lastSeen'];
DateTime? lastSeenDateTime;
// Function to format last seen time
String formatLastSeen(DateTime lastSeen) {
Duration difference = DateTime.now().difference(lastSeen);
if (difference.inDays > 0) {
return 'Last seen ${difference.inDays} days ago';
} else if (difference.inHours > 0) {
return 'Last seen ${difference.inHours} hours ago';
} else if (difference.inMinutes > 0) {
return 'Last seen ${difference.inMinutes} minutes ago';
} else {
return 'Last seen just now';
}
}
return Scaffold(
appBar: AppBar(
leading: CircleAvatar(
backgroundImage: NetworkImage(ImageLink),
),
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(name),
Text(
'Last seen $lastSeenDateTime',
style: TextStyle(fontSize: 12),
),
],
),
),
body: Center(
// child: Text('Chat with $name'),
),
);
}
}
Issue:
When attempting to display the last seen timestamp (lastSeenTimestamp) retrieved from Firestore in the app’s AppBar, I’m encountering difficulties with converting the Firestore Timestamp to a DateTime object and formatting it properly. Currently, lastSeenDateTime is null, and I’m unsure how to correctly convert the timestamp and format it to display in the app.
Expected behavior:
I expect to display the last seen status of the user in a format like “Last seen just now” or “Last seen 5 minutes ago” based on the difference between the current time and the retrieved timestamp from Firestore.
Additional context:
I’m using Firebase Firestore for storing user data, including the last seen timestamp.
The lastSeenTimestamp variable contains the Firestore Timestamp object retrieved from Firestore.
I’m looking for guidance on how to properly convert the Timestamp to DateTime and format it in Flutter.
Hussien990 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.