How to use SignalR with Flutter for Chat?

Many of us while building a mobile application, will encounter a client that will demand for built-in Chatting feature. I personally, often tend to not accept this feature request and would suggest them some other ready platforms they can use. But not this time.

Currently working on a freelance project where it became an important part of my client\’s business. I had two options: Either find an SDK online that provides all of the chatting functionality or Build your own chat APIs. Choosing the second option led me to write this blog post to share how it can be achieved.

This post will cover two areas for SignalR implementation. The first would be preparing your API (Websocket) using ASP.NET SignalR and the second would be consuming the SignalR API in your flutter application.

\”WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection.\”

Wikipedia

We will begin by creating a new .NET Core project in Visual Studio, which is straight forward. Choose ASP.NET Core Web Application.

\"\"

After the project is created, we need to add SignalR client library.

  1. In Solution Explorer, right-click the project, and select Add > Client-Side Library.
  2. In the Add Client-Side Library dialog, for Provider select unpkg.
  3. For Library, enter @microsoft/signalr@latest.
  4. Select Choose specific files, expand the dist/browser folder, and select signalr.js and signalr.min.js.
  5. Set Target Location to wwwroot/js/signalr/, and select Install.
\"\"

The class or controller which will be consumed by client, in context with SignalR is called a hub. We will create a hub for SendMessage now.

  1. In the SignalRChat project folder, create a Hubs folder.
  2. In the Hubs folder, create a ChatHub.cs file with the following code:
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

namespace SignalRChat.Hubs
{
    public class ChatHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync(\"ReceiveMessage\", user, message);
        }
    }
}

In your Startup.cs class, we will add:

public void ConfigureServices(IServiceCollection services)
	{
		services.AddRazorPages();
		//Add this
		services.AddSignalR();

	}

In your Startup.cs class, inside Configure method, amend the following:

app.UseEndpoints(endpoints =>
	{
		endpoints.MapRazorPages();
		//Add This
		endpoints.MapHub<ChatHub>(\"/chathub\");
	});

Now that SignalR server side is added, let\’s go towards client. For being able to consume the Websocket APIs in your flutter application, we would need install the signalr_core.

I would recommend having a class that is wrapped around signalr_core. Let\’s call it SignalRHelper for this article. The class will have property of HubConnection and a constructor.

class SignalRHelper{
	HubConnection connection;
	SignalRHelper(){
		connection = HubConnectionBuilder()
			.withUrl(
				hubBaseURL,
				HttpConnectionOptions(
					logging: (level, message)
						=> print(message),
				)
			).build();
	}
}

The hubBaseURL will be the URL where your SignalR is hosted plus the end point that is registered in Configure method of Startup.cs class.

Add another method in your SignalRHelper class which will be used for initiation. Let\’s call it initiateConnection. It would take BuildContext only as the parameter.

initiateConnection(BuildContext context) async {
	await connection.start();
	
	connection.on(\"ReceiveMessage\", (arguments){
		print(arguments);
		//Do what needs to be done
	});
}

In above method, the connection.on would listen to any event that is occurred on ReceiveMessage channel from the server and would print the arguments and do what needs to be done.

You have your SignalR WebSocket connection up and working.

In the end, I would like to add that if a connection is not in use, it is advised to close it instead. For that, we would add another method in SignalRHelper class:

closeConnection(BuildContext context) async {
	if(connection.state == HubConnectionState.connected)
	{
		await connection.stop();
	}
}

Please let me know in the comments if you have questions or need me to write about other important things in the world of programming and coding.

Comments

2 responses to “How to use SignalR with Flutter for Chat?”

  1. Akyl Avatar
    Akyl

    Hello!
    How to reconnect to websocket after closing app or internet failure?

    1. ghulamustafa Avatar

      Apologies for late reply. This article doesn’t cover the reconnect part but you can check it on the library’s official GitHub page. https://github.com/jamiewest/signalr_core

Leave a Reply

Your email address will not be published. Required fields are marked *