SignalR Chat Plugin for Flutter
A Flutter plugin that provides real-time chat functionality using SignalR. This plugin offers a robust, feature-rich implementation for real-time messaging in Flutter applications with automatic reconnection handling, message queuing, and connection state management.
Features
- 🔄 Real-time bi-directional communication
- 📱 Cross-platform support (iOS, Android, Web)
- 🔐 Secure WebSocket connections with optional authentication
- 🔁 Automatic reconnection handling
- 📤 Message queuing for offline/disconnected scenarios
- 📊 Connection state management and monitoring
- 🚦 Comprehensive error handling and reporting
- 📨 Message delivery status tracking
- 📤 Chat Room
📦 Installation
Installation
Add this to your package's pubspec.yaml file: https://pub.dev/packages/signalr_chat_plugin
dependencies:
signalr_chat_plugin: ^1.0.0
Basic Usage
- Initialize the plugin with your SignalR hub URL:
final chatPlugin = SignalRChatPlugin();
await chatPlugin.initSignalR(
SignalRConnectionOptions(
serverUrl: 'https://your-server.com/chathub',
accessToken: 'optional-auth-token',
),
);
- Listen for incoming messages:
chatPlugin.messagesStream.listen((message) {
print('Received message from ${message.sender}: ${message.content}');
});
- Send messages:
await chatPlugin.sendMessage('user123', 'Hello, world!');
Connection State Management
Monitor the connection state:
chatPlugin.connectionStateStream.listen((status) {
switch (status) {
case ConnectionStatus.connected:
print('Connected to the chat server');
break;
case ConnectionStatus.disconnected:
print('Disconnected from the chat server');
break;
case ConnectionStatus.reconnecting:
print('Attempting to reconnect...');
break;
case ConnectionStatus.connecting:
print('Establishing initial connection...');
break;
}
});
Error Handling
Listen for errors:
chatPlugin.errorStream.listen((error) {
print('Error occurred: $error');
});
Advanced Configuration
Configure the connection with advanced options:
final options = SignalRConnectionOptions(
serverUrl: 'https://your-server.com/chathub',
accessToken: 'your-auth-token',
reconnectInterval: Duration(seconds: 5),
maxRetryAttempts: 5,
autoReconnect: true,
useSecureConnection: true,
onError: (error) => print('Connection error: $error'),
);
await chatPlugin.initSignalR(options);
Bypass SSL Certificate Validation
If your development or staging server uses a self-signed or invalid TLS certificate, you can bypass certificate validation so the connection does not fail with a handshake error:
await chatPlugin.initSignalR(
SignalRConnectionOptions(
serverUrl: 'https://dev-server.local/chathub',
bypassSslCertificateValidation: true,
transport: HttpTransportType.webSockets,
skipNegotiation: true,
),
);
WARNING: Never enable
bypassSslCertificateValidationin production. It disables all TLS certificate checks on mobile and desktop platforms. Browsers enforce their own certificate policies and ignore this flag.
If the server does not support TLS at all, use an http:// URL instead of
https:// — bypassing certificate validation will not help when there is no
TLS to negotiate.
Message Structure
The plugin uses a ChatMessage class to handle messages:
final message = ChatMessage(
sender: 'user123',
content: 'Hello!',
messageId: 'unique-id', // Optional
status: MessageStatus.sent, // sent, delivered, or failed
);
Features Detail
Automatic Reconnection
- Configurable retry attempts and intervals
- Automatic message queue processing upon reconnection
- Connection state monitoring
Message Queuing
- Automatic queuing of messages during disconnection
- Guaranteed message delivery attempt when connection is restored
- Message status tracking (sent, delivered, failed)
Security
- Secure WebSocket connections
- Optional authentication token support
- HTTPS/WSS protocol support
Error Handling
The plugin provides comprehensive error handling:
- Connection failures
- Message delivery failures
- Server disconnections
- Authentication errors
API Reference
Main Classes
SignalRChatPlugin
initSignalR(SignalRConnectionOptions options): Initialize the chat connectionsendMessage(String sender, String content): Send a chat messagedisconnect(): Disconnect from the serverreconnect(): Manually trigger reconnectionclearMessageQueue(): Clear pending messagesdispose(): Clean up resources
SignalRConnectionOptions
serverUrl: SignalR hub URLaccessToken: Optional authentication tokenreconnectInterval: Time between reconnection attemptsmaxRetryAttempts: Maximum reconnection attemptsautoReconnect: Enable/disable automatic reconnectionuseSecureConnection: Enable/disable WSS/HTTPSbypassSslCertificateValidation: Accept invalid/self-signed certs (mobile/desktop only, not for production)
Streams
messagesStream: Receive incoming messagesconnectionStateStream: Monitor connection stateerrorStream: Listen for errors
Contributing
Contributions are welcome! Please read our contributing guidelines before submitting pull requests.
License
This project is licensed under the MIT License - see the LICENSE file for details.