Skip to main content

ichatmode_flutter_sdk 1.0.0 copy "ichatmode_flutter_sdk: ^1.0.0" to clipboard
ichatmode_flutter_sdk: ^1.0.0 copied to clipboard

retracted

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: ./packages/ichatmode_flutter_sdk

Configuration (Single Source of Truth) #

In monorepo mode, only one file needs edits:

ichatmodeclient_fl/packages/ichatmode_flutter_sdk/lib/src/config/sdk_env.dart

Set these values:

  • serverBaseUrl (single host)
  • apiToken
  • companyId
  • wsBaseUrl (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.ichatmode.com/api',
    apiKey: 'tk_xxx',
    companyId: 'company_uuid',
    userName: 'John Doe',
    userEmail: 'john@example.com',
    userId: 'stable_unique_id', // keep this stable across app launches
    wsUrl: 'wss://api.ichatmode.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://your-api.com/api',
  apiKey: 'your-api-key',
  companyId: 'your-company-id',
  
  // Optional
  userId: 'custom-user-id', // Keep stable across app restarts
  userName: 'John Doe',
  userEmail: 'john@example.com',
  debugMode: false,
  wsUrl: 'wss://your-api.com:6005', // 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 webhookUrl when creating tickets.
  • Backend stores that URL on the ticket.
  • Backend sends webhook events on:
    • ticket_created
    • ticket_message_added
    • ticket_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:

  1. request FCM permission
  2. register device token to your backend
  3. 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:

  1. Replace package import:

    // Old
    import 'package:flutter_support_chat/flutter_support_chat.dart';
       
    // New
    import 'package:ichatmode_flutter_sdk/ichatmode_flutter_sdk.dart';
    
  2. Update initialization:

    // Old
    await SupportChat.initialize(SupportChatConfig(...));
       
    // New
    await iChatMode.initialize(config: iChatModeConfig(...));
    
  3. Update API calls:

    // Old
    SupportManager().getTickets();
       
    // New
    iChatMode.tickets.getTickets();
    

API Reference #

iChatMode (Main SDK) #

  • initialize(config) - Initialize the SDK
  • updateUser(...) - Update user information
  • dispose() - Clean up resources
  • tickets - Access ticket manager
  • isInitialized - Check if SDK is initialized

TicketManager #

  • getTickets() - Get all tickets
  • getTicketMessages(ticketId) - Get messages for a ticket
  • createTicket(...) - Create a new ticket
  • replyToTicket(...) - Reply to a ticket
  • uploadAttachment(...) - Upload a file
  • joinTicketChat(ticketId) - Join real-time chat
  • leaveTicketChat(ticketId) - Leave real-time chat
  • sendTypingIndicator(ticketId, isTyping) - Send typing status

Streams #

  • onTicketCreated - New ticket created
  • onTicketUpdated - Ticket updated
  • onMessageReceived - New message received
  • onMessageUpdated - Message updated
  • onMessageDeleted - Message deleted
  • onTypingUpdate - Typing indicator updates

Support #

License #

MIT License - see LICENSE file for details.

0
likes
0
points
57
downloads

Documentation

Documentation

Publisher

unverified uploader

Weekly Downloads

Official Flutter SDK for iChatMode ticket system. Complete support chat solution with real-time messaging, file uploads, and push notifications.

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

connectivity_plus, file_picker, firebase_core, firebase_messaging, flutter, flutter_bloc, flutter_local_notifications, hive, hive_flutter, http, http_parser, image_picker, intl, mime, shared_preferences, uuid, web_socket_channel

More

Packages that depend on ichatmode_flutter_sdk