ichatmode_flutter_sdk 1.0.2
ichatmode_flutter_sdk: ^1.0.2 copied to clipboard
Official Flutter SDK for iChatMode ticket system. Complete support chat solution with real-time messaging, file uploads, and push notifications.
iChatMode Flutter SDK #
Production-grade support SDK for Flutter. Provides business logic only (no UI), so teams can build their own UI while using the same API, real-time, and notifications stack.
What You Get #
- Zero UI dependencies
- Real-time updates (WebSocket)
- File uploads and rich attachments
- Offline caching
- Local + push notifications
- Typed models and predictable APIs
Requirements #
- Flutter 3.x
- Dart 3.x
Installation #
dependencies:
ichatmode_flutter_sdk: ^1.0.0
# Optional (push notifications)
firebase_core: ^2.24.2
firebase_messaging: ^14.7.10
Monorepo (this repo) #
dependencies:
ichatmode_flutter_sdk:
path: ../ichatmode_flutter_sdk
Configuration (Single Source of Truth) #
In monorepo mode, only one file needs edits:
ichatmode_flutter_sdk/lib/src/config/sdk_env.dart
Set these values:
serverBaseUrl(single host)apiTokencompanyIdwsBaseUrl(only if WebSocket runs on a different port)defaultUniqueId(optional fallback)
Do not commit real secrets in the SDK. Keep these as placeholders in the package and set real values only in your host app or private config.
All API + webhook URLs are derived automatically from serverBaseUrl.
Quick Start #
Option A: Plug-and-play (Monorepo) #
import 'package:ichatmode_flutter_sdk/ichatmode_flutter_sdk.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
await iChatMode.initializeWithDefaults(
userName: 'Demo User',
userEmail: 'demo@example.com',
enablePushNotifications: true,
);
runApp(const MyApp());
}
Option B: Standalone SDK #
await iChatMode.initialize(
config: iChatModeConfig(
apiUrl: 'https://api.example.com/api',
apiKey: 'tk_xxx',
companyId: 'company_uuid',
userName: 'John Doe',
userEmail: 'john@example.com',
uniqueId: 'stable_unique_id', // keep this stable across app launches
wsUrl: 'wss://api.example.com/ws', // optional if WS is separate
debugMode: false,
),
);
Core Usage #
Ticket List #
class TicketListScreen extends StatefulWidget {
@override
_TicketListScreenState createState() => _TicketListScreenState();
}
class _TicketListScreenState extends State<TicketListScreen> {
List<Ticket> tickets = [];
bool loading = true;
@override
void initState() {
super.initState();
_loadTickets();
_listenToUpdates();
}
void _loadTickets() async {
try {
final fetchedTickets = await iChatMode.tickets.getTickets();
setState(() {
tickets = fetchedTickets;
loading = false;
});
} catch (e) {
print('Error loading tickets: $e');
setState(() => loading = false);
}
}
void _listenToUpdates() {
// Listen for new tickets
iChatMode.tickets.onTicketCreated.listen((ticket) {
setState(() {
tickets.insert(0, ticket);
});
});
// Listen for ticket updates
iChatMode.tickets.onTicketUpdated.listen((updatedTicket) {
setState(() {
final index = tickets.indexWhere((t) => t.id == updatedTicket.id);
if (index != -1) {
tickets[index] = updatedTicket;
}
});
});
}
@override
Widget build(BuildContext context) {
if (loading) {
return Scaffold(
appBar: AppBar(title: Text('Support Tickets')),
body: Center(child: CircularProgressIndicator()),
);
}
return Scaffold(
appBar: AppBar(title: Text('Support Tickets')),
body: ListView.builder(
itemCount: tickets.length,
itemBuilder: (context, index) {
final ticket = tickets[index];
return ListTile(
title: Text(ticket.subject),
subtitle: Text('Status: ${ticket.status}'),
trailing: Text(ticket.priority),
onTap: () => _openTicket(ticket),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: _createTicket,
child: Icon(Icons.add),
),
);
}
void _openTicket(Ticket ticket) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TicketChatScreen(ticket: ticket),
),
);
}
void _createTicket() async {
try {
final ticket = await iChatMode.tickets.createTicket(
subject: 'New Support Request',
message: 'I need help with...',
priority: 'medium',
);
setState(() {
tickets.insert(0, ticket);
});
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error creating ticket: $e')),
);
}
}
}
Configuration Options #
iChatModeConfig(
// Required
apiUrl: 'https://api.example.com/api',
apiKey: 'your-api-key',
companyId: 'your-company-id',
// Optional
uniqueId: 'custom-user-id', // Keep stable across app restarts
userName: 'John Doe',
userEmail: 'john@example.com',
debugMode: false,
wsUrl: 'wss://api.example.com/ws', // Optional if WS is separate
websocketTimeout: 30, // seconds
apiTimeout: 30, // seconds
maxFileSize: 25 * 1024 * 1024, // 25MB
allowedFileTypes: [
'image/jpeg', 'image/png', 'application/pdf', // etc.
],
enableOfflineMode: true,
enablePushNotifications: false, // Set true only if Firebase is configured
metadata: {'app_version': '1.0.0'}, // Custom metadata
webhookUrl: 'https://client-backend.example.com/webhooks/ichatmode', // Optional
)
Logging #
SDK logs are controlled by debugMode. Keep it false for production to avoid noisy output.
WebSocket Notes #
The backend WebSocket server uses /ws by default. If the WS service runs on a
different port, pass wsUrl.
Webhooks (Plug-and-Play Notifications) #
If the client already has their own notification system, use webhooks instead of sharing FCM secrets.
How it works #
- SDK sends
webhookUrlwhen creating tickets. - Backend stores that URL on the ticket.
- Backend sends webhook events on:
ticket_createdticket_message_addedticket_status_changed/ticket_updated
Example webhook payload #
{
"event": "ticket_message_added",
"timestamp": "2026-01-05T08:22:14.123Z",
"data": {
"ticket_id": "uuid",
"ticket_number": "#0123",
"company_id": "uuid",
"unique_id": "customer-unique-id",
"status": "open",
"priority": "P3",
"subject": "Payment Issue",
"user_name": "Mobile App User",
"user_email": "user@example.com",
"source": "mobile_app",
"message": {
"id": "uuid",
"content": "Any update?",
"sender_type": "user",
"sender_name": "Mobile App User",
"created_at": "2026-01-05T08:22:14.123Z"
},
"ticket": { "id": "uuid", "status": "open" }
}
}
Sample webhook handler (Node.js/Express) #
import express from 'express';
const app = express();
app.use(express.json());
app.post('/webhooks/ichatmode', async (req, res) => {
const { event, data } = req.body;
if (event === 'ticket_message_added') {
// Trigger your own push notification here (FCM/APNS/etc)
const ticketId = data.ticket_id;
const uniqueId = data.unique_id;
const messagePreview = data.message?.content;
}
if (event === 'ticket_status_changed') {
// Handle status updates
}
res.status(200).json({ ok: true });
});
app.listen(3001, () => console.log('Webhook server listening'));
Signature verification (optional) #
If you set a webhook secret, the backend can sign payloads using:
x-webhook-signature(HMAC SHA256)x-webhook-timestamp
Verify those headers on your server to ensure payload authenticity.
Node.js (HMAC SHA256) example
import crypto from 'crypto';
function verifySignature(payload, signature, timestamp, secret) {
const body = JSON.stringify(payload);
const signed = crypto
.createHmac('sha256', secret)
.update(`${timestamp}.${body}`)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(signed, 'utf8'),
Buffer.from(signature, 'utf8')
);
}
Push Notifications (FCM) #
If enablePushNotifications is true, the SDK will:
- request FCM permission
- register device token to your backend
- receive push notifications for agent messages and status updates
Make sure your backend has FCM credentials configured (server-side only).
If Firebase isn't configured in the app, keep enablePushNotifications: false.
Foreground messages are shown via local notifications; background messages are shown by the OS for notification payloads.
Core Features #
Creating Tickets #
// Simple ticket
final ticket = await iChatMode.tickets.createTicket(
subject: 'Payment Issue',
message: 'I was charged twice for my order',
priority: 'high',
tags: ['billing', 'urgent'],
);
// Ticket with attachments
final ticket = await iChatMode.tickets.createTicket(
subject: 'Bug Report',
message: 'App crashes when I tap this button',
attachmentPaths: ['/path/to/screenshot.png'],
metadata: {'device': 'iPhone 12', 'os': 'iOS 15.0'},
);
Real-time Messaging #
class TicketChatScreen extends StatefulWidget {
final Ticket ticket;
TicketChatScreen({required this.ticket});
@override
_TicketChatScreenState createState() => _TicketChatScreenState();
}
class _TicketChatScreenState extends State<TicketChatScreen> {
List<Message> messages = [];
@override
void initState() {
super.initState();
_loadMessages();
_joinChat();
_listenToMessages();
}
void _loadMessages() async {
final result = await iChatMode.tickets.getTicketMessages(widget.ticket.id);
setState(() {
messages = result.messages;
});
}
void _joinChat() {
// Join real-time chat room
iChatMode.tickets.joinTicketChat(widget.ticket.id);
}
void _listenToMessages() {
// Listen for new messages
iChatMode.tickets.onMessageReceived.listen((message) {
if (message.ticketId == widget.ticket.id) {
setState(() {
messages.add(message);
});
}
});
}
void _sendMessage(String text) async {
try {
await iChatMode.tickets.replyToTicket(
ticketId: widget.ticket.id,
message: text,
);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to send message: $e')),
);
}
}
@override
void dispose() {
// Leave chat room
iChatMode.tickets.leaveTicketChat(widget.ticket.id);
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.ticket.subject)),
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: messages.length,
itemBuilder: (context, index) {
final message = messages[index];
return MessageBubble(message: message);
},
),
),
MessageInput(onSend: _sendMessage),
],
),
);
}
}
File Uploads #
// Upload with message
await iChatMode.tickets.replyToTicket(
ticketId: ticketId,
message: 'Here are the screenshots',
attachmentPaths: [
'/path/to/screenshot1.png',
'/path/to/screenshot2.png',
],
);
// Upload standalone attachment
final attachment = await iChatMode.tickets.uploadAttachment(
ticketId: ticketId,
filePath: '/path/to/document.pdf',
);
Typing Indicators #
// Send typing indicator
iChatMode.tickets.sendTypingIndicator(ticketId, true); // Start typing
iChatMode.tickets.sendTypingIndicator(ticketId, false); // Stop typing
// Listen for typing updates
iChatMode.tickets.onTypingUpdate.listen((update) {
if (update.ticketId == currentTicketId) {
setState(() {
typingUsers = update.users; // Map<String, String> userId -> userName
});
}
});
Local Notifications (No FCM) #
If Firebase is not configured, the SDK still shows local notifications while the app is in the foreground. Background notifications require FCM.
Error Handling #
try {
final tickets = await iChatMode.tickets.getTickets();
} on ApiException catch (e) {
print('API Error: ${e.message} (Status: ${e.statusCode})');
} on NetworkException catch (e) {
print('Network Error: ${e.message}');
} on iChatModeException catch (e) {
print('SDK Error: ${e.message}');
} catch (e) {
print('Unknown Error: $e');
}
Offline Support #
The SDK automatically caches data locally and works offline:
// This will return cached data instantly, then refresh in background
final tickets = await iChatMode.tickets.getTickets();
// Force refresh from server
final freshTickets = await iChatMode.tickets.getTickets(forceRefresh: true);
Advanced Usage #
Custom User Management #
// Update user info (e.g., after login)
await iChatMode.updateUser(
userId: 'user123',
userName: 'Jane Smith',
userEmail: 'jane@example.com',
metadata: {'role': 'premium'},
);
Direct API Access #
// Access API service directly for custom requests
final apiService = iChatMode.instance.apiService;
final response = await apiService.makeCustomRequest('/custom-endpoint');
WebSocket Events #
// Access WebSocket service for custom events
final wsService = iChatMode.instance.websocketService;
wsService.emit('custom:event', {'data': 'value'});
Migration from Existing Package #
If you're migrating from flutter_support_chat:
-
Replace package import:
// Old import 'package:flutter_support_chat/flutter_support_chat.dart'; // New import 'package:ichatmode_flutter_sdk/ichatmode_flutter_sdk.dart'; -
Update initialization:
// Old await SupportChat.initialize(SupportChatConfig(...)); // New await iChatMode.initialize(config: iChatModeConfig(...)); -
Update API calls:
// Old SupportManager().getTickets(); // New iChatMode.tickets.getTickets();
API Reference #
iChatMode (Main SDK) #
initialize(config)- Initialize the SDKupdateUser(...)- Update user informationdispose()- Clean up resourcestickets- Access ticket managerisInitialized- Check if SDK is initialized
TicketManager #
getTickets()- Get all ticketsgetTicketMessages(ticketId)- Get messages for a ticketcreateTicket(...)- Create a new ticketreplyToTicket(...)- Reply to a ticketuploadAttachment(...)- Upload a filejoinTicketChat(ticketId)- Join real-time chatleaveTicketChat(ticketId)- Leave real-time chatsendTypingIndicator(ticketId, isTyping)- Send typing status
Streams #
onTicketCreated- New ticket createdonTicketUpdated- Ticket updatedonMessageReceived- New message receivedonMessageUpdated- Message updatedonMessageDeleted- Message deletedonTypingUpdate- Typing indicator updates
Support #
- 📧 Email: support@ichatmode.com
- 📖 Documentation: https://docs.ichatmode.com
- 🐛 Issues: https://github.com/your-org/ichatmode-flutter-sdk/issues
License #
MIT License - see LICENSE file for details.