How to Store and Retrieve Flutter Chat Conversation Data?
In this article, we have explained how to store and retrieve the Flutter Chat conversation data from Flutter Firebase.
To begin this, we need to create a list of messages in a JSON file, which can be added to the database by importing the JSON file in the Firebase. For real-time message updates, Firebase push() method is used to add new messages to the database. To fetch the data from the Firebase, we use the StreamBuilder, which listens for changes in the database and updates the message list whenever new messages are added.
The following steps will guide you on integrating SfChat with Firebase for storing and retrieving conversation data.
Step 1: How to integrate the Firebase with Flutter project.
Refer to the following guidelines to integrate Firebase into your project: firebase project guidelines.
Once Firebase is integrated into your project, a firebase.json file will be generated in the sample directory, and a firebase_options.dart file will be created within the lib folder of the sample project.
Step 2: Import the required packages.
After completing the Firebase project configuration, add the following packages in the pubspec.yaml file to use Firebase and the Chat widget in this project:
dependencies:
syncfusion_flutter_chat: ^27.1.48
firebase_core: ^1.1.0
firebase_database: ^6.1.2
Step 3: How to create the chat message for this project.
We are using the ChatMessage type as the reference for creating the message list in this project. The ChatMessage model contains properties like text, time, and the ChatAuthor which includes the author ID and author name. The text represents the message entered by the user, while the time records when the message is sent. The author ID is used to distinguish between different users.
Step 4: How to create the chat message JSON file for this project.
First, create a JSON file locally, which will not be included in the sample project. Then, populate this JSON file with a list of chat messages using the provided JSON structure.
Code snippet for JSON structure:
{
"messages": {
"msg1": {
"text": "Hey! How's it going?",
"time": "2024-10-08T12:00:00Z",
"authorId": "00-00230-23423",
"authorName": "Sam"
},
"msg2": {
"text": "I'm good, thanks! Just enjoying the weekend.",
"time": "2024-10-08T12:02:00Z",
"authorId": "00-00230-23424",
"authorName": "John"
}
}
}
Step 5: How to import the JSON file to the Firebase.
First, navigate to the Firebase console and go to the Realtime Database section, where we will import the locally created JSON file into the database and also change the read and write rule to true in rules section to update and retrieve the data to the database, as shown in the provided image.
First, navigate to the Firebase console and access the Realtime Database section. Here, we will import the locally created JSON file into the database as per the following image.
Additionally, in the Rules section, update the read and write permissions by setting them to true to allow data updates and retrieval from the database, as demonstrated in the following image.
Step 6: How to fetch message data from the database using StreamBuilder.
We used the StreamBuilder to fetch data from Firebase. A stream allows real-time updates, so when a new message is added to the database, it is automatically reflected in the message list. If an error occurs during data retrieval, an error message is displayed. When new data is fetched, the existing message list is cleared to avoid duplicates. Each message is then processed into a ChatMessage object, which includes the text, time, and author information such as ID and name. The SfChat widget then renders these messages in the conversation area.
Code snippet:
final DatabaseReference _messageStream = FirebaseDatabase.instance.ref('messages');
StreamBuilder<DatabaseEvent>(
stream: _messageStream.onValue,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
final data = snapshot.data?.snapshot.value as Map<dynamic, dynamic>?;
if (data != null && data.isNotEmpty) {
_messages.clear();
data.forEach((key, value) {
final message = ChatMessage(
text: value['text'],
time: DateTime.parse(value['time']),
author: ChatAuthor(
id: value['authorId'],
name: value['authorName'],
),
);
_messages.add(message);
});
_messages.sort((a, b) => a.time.compareTo(b.time));
}
return SfChat(
messages: _messages,
outgoingUser: 'Sam',
);
},
)
Step 7: How to push the conversation data directly to the Firebase.
The push() method adds the conversation message to the Firebase Realtime Database, by storing the message text, time, author ID, and author name from the ChatMessage object. The _sendMessageToFirebase method is called when the action button onPressed callback is triggered, which add new message to the message list. Refer the following code snippet:
Future<void> _sendMessageToFirebase(ChatMessage message) async {
await _messageStream.push().set({
'text': message.text,
'time': message.time.toIso8601String(),
'authorId': message.author.id,
'authorName': message.author.name,
});
}
Finally, the SfChat widget will showcase the message retrieved from the database in the chat conversation area.
Output:
Here is the final demo with chat widget:
Conclusion:
I hope you enjoyed learning about how to work with firebase and flutter chat to store and retrieve the conversation data.
You can refer to our Flutter Chat feature tour page to know about its other groundbreaking feature representations and documentation and how to quickly get started for configuration specifications.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!