Connecting the Dots: Integrating .NET Core SignalR with Flutter

Ashish Sharma
5 min readSep 2, 2023

--

In the ever-evolving world of app development, staying connected with your users is paramount. Real-time features like chat, notifications, or live updates have become the gold standard. But how do you achieve that real-time magic in a Flutter app? Enter .NET Core SignalR, a fantastic tool for building real-time applications, and Flutter, Google’s UI toolkit for crafting nifty apps.

In this article, we’ll take a journey into integrating .NET CoreSignalR with Flutter, and we’ll keep it simple, promise!

Why Real-Time Matters

Before diving into the tech stuff, let’s grasp why real-time features are cool:

  • Live Updates: Think of a live sports score app. With real-time updates, you get the latest scores without refreshing the page.
  • Chat Apps: You send a message; your friend receives it instantly. That’s real-time magic at work.
  • Collaborative Tools: Imagine Google Docs. Real-time collaboration makes editing with others seamless.

Now, let’s unlock these real-time powers for your Flutter app.

Meet .NET Core SignalR

.NET CoreSignalR is like a magical messenger between your server and clients. It enables real-time communication with ease. On the server side, you can use .NET technologies like ASP.NET. On the client side, well, that’s where Flutter shines.

Setting Up .NET Core SignalR

Integrating .NET Core SignalR with Flutter begins with preparing your .NET project to serve as the backend for real-time communication. Below are the steps to set up a .NET Core SignalR project, including configuring dependencies and creating hubs:

Step 1: Create a New ASP.NET Core Project

Begin by creating a new ASP.NET Core project or use an existing one if you have a project in progress.

Step 2: Install the SignalR Package

To enable SignalR functionality in your ASP.NET Core project, follow these steps:

  1. Open your project in Visual Studio or your preferred code editor.
  2. In your project’s Startup.cs file, locate the ConfigureServices method and add the following line to register SignalR services:
services.AddSignalR();

In the Configure method of the same file, add the SignalR route:

app.UseEndpoints(endpoints =>
{
endpoints.MapHub<YourHubName>("/yourHubPath");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action}/{id?}");
});

Replace YourHubName with the name of your SignalR hub class and /yourHubPath with the desired URL path for the hub.

Step 3: Create a SignalR Hub

Create a SignalR hub class in your ASP.NET Core project. The hub class represents the hub that clients will connect to for real-time communication. Here’s an example of a SignalR hub:

using Microsoft.AspNetCore.SignalR;
public class YourHubName : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}

Step 4: Configure CORS (Cross-Origin Resource Sharing)

To allow communication with your SignalR hub from a Flutter app running on a different domain, configure CORS settings. In your Startup.cs file, add CORS policies to enable cross-origin requests:

services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});

And in the Configure method:

app.UseCors("AllowAll");

Step 5: Start the Hub

Make sure your SignalR hub is running when your ASP.NET Core application starts. In the Configure method of your Startup.cs, start the hub:

app.UseSignalR(routes =>
{
routes.MapHub<YourHubName>("/yourHubPath");
});

Now, your ASP.NET Core SignalR project is configured to accept connections from Flutter clients. Ensure that your ASP.NET Core application is running before proceeding to set up the Flutter side for real-time communication.

Now, let’s dive into the exciting part

Let’s keep it simple with a chat app example. Here’s a basic Flutter code snippet:

Step 1: Add the “signalr_client” Dependency

Open your Flutter project’s pubspec.yaml file and add the "signalr_client" package as a dependency:

dependencies:
flutter:
sdk: flutter
signalr_client: ^latest_version

Don’t forget to run flutter pub get to fetch the package.

Step 2: Create a Flutter UI

Design the user interface (UI) for your Flutter app. You can create a chat-like interface with a text input field, a message display area, and a send button. Ensure you have the necessary widgets, such as TextField, ListView.builder, and ElevatedButton.

Step 3: Set Up the SignalR Connection

In your Flutter code (typically in a Dart file), import the “signalr_client” package and configure the SignalR connection to your .NET SignalR hub. Replace 'https://your-signalr-hub-url' with the actual URL of your SignalR hub.

import 'package:signalr_client/signalr_client.dart';

final hubConnection = HubConnectionBuilder().withUrl('https://your-signalr-hub-url').build();

Step 4: Connect to the Hub

Initialize the SignalR connection and start it. You can do this when the app starts or in response to a user action, such as pressing a “Connect” button.

await hubConnection.start();

Step 5: Define Hub Event Handlers

Create event handlers to handle incoming messages from the SignalR hub. In this example, we’ll handle a “ReceiveMessage” event. You can add these handlers after starting the connection.

hubConnection.on('ReceiveMessage', (arguments) {
// Handle incoming message here
String user = arguments[0];
String message = arguments[1];

// Update your UI with the received message
});

Step 6: Send Messages

Implement a function to send messages to the hub. This function can be called when the user presses a “Send” button or similar UI action.

void sendMessage(String user, String message) {
hubConnection.invoke('SendMessage', args: [user, message]);
}

Step 7: Display Messages

Update your UI to display incoming and outgoing messages. You can use a ListView.builder widget to display a chat-like conversation.

Step 8: Handle UI Interactions

In your Flutter app, create UI elements and interactions to allow users to send messages and interact with the SignalR hub.

Step 9: Test the Real-Time Communication

Run your Flutter app and the .NET Core SignalR server. Test the real-time communication by sending and receiving messages in your Flutter app. You should see messages appearing in real time as they are sent and received.

Step 10: Add Error Handling

Implement error handling to gracefully handle any connection issues or failures that may occur during real-time communication.

Full code of flutter main.dart.

.Net Core Hub.cs

In this SignalR hub:

  • The SendMessage method is invoked by clients to send messages to the hub. It broadcasts the received message to all connected clients using the "ReceiveMessage" event.
  • The OnConnectedAsync method is called when a client connects to the hub. You can add custom logic here, such as notifying other clients about the new connection.
  • The OnDisconnectedAsync method is called when a client disconnects from the hub. Similar to the OnConnectedAsync method, you can add custom logic here, such as notifying other clients about the disconnection.

Make sure to register this hub in your ASP.NET Core application’s startup configuration, as shown in previous responses, and replace the placeholder "https://your-signalr-hub-url" in your Flutter app with the actual URL where this hub is hosted.

Conclusion

In this real-time chat app, we’ve demonstrated the power of Flutter and .Net Core SignalR working together seamlessly. You’ve witnessed how easy it is to create a dynamic chat interface and exchange messages in real-time. Now, armed with this knowledge, you can explore further and build even more exciting real-time applications. If you have any questions or need further assistance, feel free to reach out. Happy coding! 🚀

--

--

Ashish Sharma

TheFlutterist: Teaching Flutter in the most playful way possible. Join me in the land of widgets and hot reloads! http://flutterist.in/