---
title: "Save Chat History to Firebase Realtime Database using the .NET MAUI Chat Control"
published_at: "2025-02-10T10:42:54+00:00"
modified_at: "2025-03-20T08:28:48+00:00"
url: "https://www.syncfusion.com/blogs/post/save-chat-to-firebase-database-maui"
excerpt: "Learn to save chat messages in the Firebase Realtime Database using the .NET MAUI Chat control."
taxonomy_category:
  - ".NET MAUI"
  - "Cloud"
  - "Desktop"
  - "Development"
  - "Mobile"
  - "UI"
taxonomy_post_tag:
  - ".NET MAUI"
  - "Chat"
  - "Cloud Service"
  - "database"
  - "desktop"
  - "Firebase"
  - "MAUI"
  - "Mobile"
---

# Save Chat History to Firebase Realtime Database using the .NET MAUI Chat Control

[Piruthiviraj Malaimelraj](https://www.syncfusion.com/blogs/author/piruthiviraj-malaimelraj)

![Saving Chat Conversations to Firebase Realtime Database using .NET MAUI Chat](https://www.syncfusion.com/blogs/wp-content/uploads/2025/02/Saving-Chat-Conversations-to-Firebase-Realtime-Database-using-.NET-MAUI-Chat.jpg)


**TL;DR:** Let’s see how to save chat conversations using Firebase Realtime Database in a .NET MAUI app. We’ll set up Firebase, configure the database, and integrate it with the .NET MAUI Chat control. Messages will be stored and retrieved in real time using Firebase queries. This guide helps you build a seamless and interactive chat experience.

Syncfusion [.NET MAUI Chat](https://www.syncfusion.com/maui-controls/maui-chat)
 control, or conversational UI, provides a modern chat experience. It is a flexible control that displays conversations between two or more users in a fully customizable layout. You can show messages with all types of content, such as text, images, hyperlinks, cards, and more, and even integrate the component with chatbot frameworks.

In this blog, we’ll see how to save chat conversions to the [Firebase Realtime Database](https://firebase.google.com/docs/database)
 using the .NET MAUI Chat control.

## Setting up the Firebase Realtime Database

Creating a Firebase Realtime Database involves a few simple steps, including setting up your Firebase project, enabling the database, and configuring it for your app. Here’s a detailed guide:

### Create a Firebase project

1. First, go to the [Firebase console](https://console.firebase.google.com/) .
2. Click on the**Create a Project** option.
3. Then, enter the project name and click continue. Refer to the following image.

![Create a firebase project](https://www.syncfusion.com/blogs/wp-content/uploads/2025/01/image001-3.png)

### Create the database

Let’s set up a Firebase Realtime Database by following these steps:

1. Navigate to the **Realtime Database** section under the**Build** menu. ![Navigate to the Realtime Database](https://www.syncfusion.com/blogs/wp-content/uploads/2025/01/image002-1.png)
2. Choose the**Create Database** option. ![Choose the Create Database option](https://www.syncfusion.com/blogs/wp-content/uploads/2025/01/image003-3.png)
3. Choose a database [location](https://firebase.google.com/docs/projects/locations) and configure the initial security rules for access. ![Choose a database location and configure the initial security rules](https://www.syncfusion.com/blogs/wp-content/uploads/2025/01/image004-2.png)
4. Click **Next** to configure the [security rules](https://firebase.google.com/docs/database/security) for your database to secure your data.
5. Then, select the **Start in test mode** option and choose the ** Enable** option at the bottom. ![Select the Start in test mode option](https://www.syncfusion.com/blogs/wp-content/uploads/2025/01/image005-2.png)
6. Now, we’ve successfully created the Firebase Realtime database. Get the database URL from the Firebase console. Refer to the following image.![Get the Database URL from the Firebase console](https://www.syncfusion.com/blogs/wp-content/uploads/2025/01/image006-2.png)

## Configure Firebase in your .NET MAUI app

1. Create a new .NET MAUI project and install the [FirebaseDatabase.net](https://www.nuget.org/packages/FirebaseDatabase.net) NuGet package. ![Install FirebaseDatabase.net NuGet package](https://www.syncfusion.com/blogs/wp-content/uploads/2025/01/image008-2.png)
2. Then, create the database model class with the required properties/data.``` public class ChatMessage { public Author Author { get; set; } public string? Content { get; set; } public DateTime Timestamp { get; set; } public string Url { get; set; } public ImageSource Thumbnail { get; set; } } ```
3. In the **RealtimeDatabaseService** class, create the ** FirebaseClient** instance with the Realtime database URL from the Firebase console.``` using Firebase.Database; using Firebase.Database.Query; namespace ChatMaui { internal class RealtimeDatabaseService { internal FirebaseClient DatabaseClient { get; set; } public RealtimeDatabaseService() { var firebaseDatabaseUrl = "https://chatdatabase-b9a22-default-rtdb.firebaseio.com/"; // Initialize FirebaseClient. DatabaseClient = new FirebaseClient(firebaseDatabaseUrl); } } } ```
4. Now, include the code logic to post a new request and store the instance of **ChatMessage**, which holds the details of the chat message, using the ** PostAsync** method. Here, the ** ChatSource** indicates the collection or data structure of the saved data.``` internal async Task SendMessageAsync(ChatMessage content) { await DatabaseClient .Child("ChatSource") .PostAsync(content); } ```

## Add and configure the .NET MAUI Chat control

First, refer to the .NET MAUI Chat control’s [getting started](https://help.syncfusion.com/maui/chat/getting-started)
 documentation.

### Create the ViewModel

Create the [CurrentUser](https://help.syncfusion.com/maui/chat/messages#setting-current-user-for-conversation)
 property of type **Author** in the ** ViewModel** class. Then, create the [TextMessage](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.Chat.TextMessage.html)
 instance. Set values for the **Message.**** Author** and ** Message.Text** properties and add it to the ** ViewModel.Messages** collection.

Refer to the available [message types](https://help.syncfusion.com/maui/chat/messages)
 in .NET MAUI Chat.

```
public class ViewModel : INotifyPropertyChanged
{
        . . .
        . . .
        public Author CurrentUser
        {
            get
            {
                return this.currentUser;
            }
            set
            {
                this.currentUser = value;
                RaisePropertyChanged("CurrentUser");
            }
        }

        public ObservableCollection<object> Messages
        {
            get
            {
                return this.messages;
            }

            set
            {
                this.messages = value;
                RaisePropertyChanged(nameof(this.messages));    
            }
        }
}
```

Now, bind the **CurrentUser** and ** Messages** properties from the ViewModel to the ** SfChat** control.

```
<ContentPage.BindingContext>
    <local:ViewModel />
</ContentPage.BindingContext>

<ContentPage.Content>
    <sfchat:SfChat x:Name="sfChat"
                   Messages="{Binding Messages}"
                   CurrentUser="{Binding CurrentUser}" />
</ContentPage.Content>
```

### Implementing the chat saving and retrieval logic

Let’s create the **LoadMessages** method in the ** ViewModel** class and implement the ** Subscribe** query to retrieve the data and notify the changes in your database.

In this method, we’ll retrieve the existing data from the database, create a **TextMessage,** and add it to the ** Messages** collection. This ** Subscribe** event will be invoked when a new message is added on-demand in the ** SfChat** control.

```
public IDisposable LoadMessages()
{
    return databaseClient.Child("ChatSource")
        .AsObservable<ChatMessage>().Subscribe((data) =>
        {
            if (data.Object != null && data.EventType == Firebase.Database.Streaming.FirebaseEventType.InsertOrUpd
            {
                Author author;
                if (data.Object.Author.Name == CurrentUser.Name)
                {
                    author = CurrentUser;
                }
                else
                {
                    author = new Author() 
                    { 
                        Name = data.Object.Author.Name, 
                        Avatar = data.Object.Author.Avatar != null ? data.Object.Author.Avatar : "steven.png" 
                    };
                }

                MainThread.BeginInvokeOnMainThread(() =>
                {
                    var message = new TextMessage()
                    {
                        Author = author,
                        Text = data.Object!.Content!,
                        DateTime = data.Object.Timestamp
                    };

                    this.Messages.Add(message);
                });
            }
        });
}
```

Then, add the following code in the **Appearing** event of the ** ContentPage** to wire the ** Subscribe** event handler to an observable sequence.

```
private void OnAppearing(object? sender, EventArgs e)
{
    this.SuscribeInGrupalChat = viewModel.LoadMessages();
}
```

### Save the new message to the Firebase Realtime Database

Configure the [SendMessage](https://help.syncfusion.com/maui/chat/messages#sending-message)
 event of the .NET MAUI Chat control and create an instance of **ChatMessage** by using ** SendMessageEventArgs** details. Then, invoke the ** SendMessageAsync** method to invoke the ** PostAsync** query of Firebase. Once the message is stored in the database, the ** Subscribe** event handler will be notified, and that new message will be added to the .NET MAUI Chat control manually.

```
chat.SendMessage += OnSendMessage;

private async void OnSendMessage(object? sender, SendMessageEventArgs e)
{
    // Set Handled=True to prevent adding the new message automatically and enable the user to add it manually.
    e.Handled = true;

    var newMessage = e.Message?.Text;
    
    var dt = DateTime.Now;

    chat.Editor.Text = string.Empty;

    if (!string.IsNullOrEmpty(newMessage) && !string.IsNullOrEmpty(viewModel.CurrentUser.Name))
    {
        await viewModel.FireBaseDatabase.SendMessageAsync(new ChatMessage
        {                    
            Author = viewModel.CurrentUser,
            Content = newMessage,
            Timestamp = dt,
        });
    }
}
```

With the Firebase Realtime Database and .NET MAUI Chat control, we can easily build a robust chat app with minimal configuration. This setup provides an efficient way to save, retrieve, and display chat messages in real time.

Refer to the following images.

![Building a robust chat app using the .NET MAUI Chat control and Firebase Realtime Database](https://www.syncfusion.com/blogs/wp-content/uploads/2025/01/image009-1.png)

Building a chat app using the .NET MAUI Chat control and Firebase Realtime Database

![Saving chat conversations to Firebase Realtime Database using .NET MAUI Chat](https://www.syncfusion.com/blogs/wp-content/uploads/2025/01/image010-1.png)

Saving chat conversations to Firebase Realtime Database using .NET MAUI Chat

## GitHub demo

For more details, refer to the [saving chat conversations to Firebase Realtime Database using the .NET MAUI Chat control GitHub demo](https://github.com/SyncfusionExamples/save-chat-messages-to-firebase-realtime-database-net-maui-chat)
.


## Conclusion

Thanks for reading! In this blog, we’ve seen how to create a chat app using the Syncfusion [.NET MAUI Chat](https://www.syncfusion.com/maui-controls/maui-chat)
 control and Firebase Realtime Database. We’ve also seen how to save and retrieve chat data to the database. Try the steps discussed in this blog and leave your feedback in the comments below!

Existing customers can access the new version of Essential Studio® on the [License and Downloads](https://www.syncfusion.com/account)
 page. If you aren’t a Syncfusion customer, try our 30-day [free trial](https://www.syncfusion.com/downloads)
 to experience our fantastic features.

If you have any questions or require assistance, you can contact us through our [support forums](https://www.syncfusion.com/forums)
, [support portal](https://support.syncfusion.com/agent/tickets?brandids=all)
, or [feedback portal](https://www.syncfusion.com/feedback)
. We are always happy to assist you!

## Related Blogs



[Easily Bind SQLite Database and Perform CRUD Actions in .NET MAUI DataGrid](https://www.syncfusion.com/blogs/post/bind-sqlite-perform-crud-in-maui-grid)



[Introducing the New .NET MAUI Bottom Sheet Control](https://www.syncfusion.com/blogs/post/new-dotnet-maui-bottom-sheet-control)



[How to Easily Load JSON Data in .NET MAUI TreeView?](https://www.syncfusion.com/blogs/post/load-json-data-dotnet-maui-treeview)



[Create 3D Column Charts in .NET MAUI to Display America’s Top 10 Sports](https://www.syncfusion.com/blogs/post/maui-toolkit-3d-column-chart-for-sports)
