Skip to main content

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

Official Flutter SDK for iChatMode ticket system. Logic-only SDK - no UI components. Build your own UI with your app's theme!

iChatMode Flutter SDK #

pub package License

Lightweight Flutter SDK for iChatMode ticketing system with real-time messaging, file attachments, and push notifications.

No UI included - Pure business logic for maximum flexibility.


Features #

  • ✅ Complete ticket management (CRUD operations)
  • ✅ Real-time messaging via WebSocket
  • ✅ File attachments (images, documents)
  • ✅ Offline-first with local caching
  • ✅ Push notifications (Firebase)
  • ✅ Typing indicators
  • ✅ Auto-reconnect with exponential backoff
  • ✅ Type-safe with null-safety
  • ✅ Multi-platform (iOS, Android, Web, Desktop)

Installation #

Add to pubspec.yaml:

dependencies:
  ichatmode_flutter_sdk: ^1.0.4

Run:

flutter pub get

Platform Setup #

Android - Add to AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

iOS - Add to Info.plist:

<key>NSCameraUsageDescription</key>
<string>Upload images to support tickets</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Select images for support tickets</string>

Quick Start #

1. Initialize SDK #

import 'package:ichatmode_flutter_sdk/ichatmode_flutter_sdk.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await iChatMode.initialize(
    config: iChatModeConfig(
      apiUrl: 'https://your-server.com/api',
      apiKey: 'tk_your_api_key',
      companyId: 'your-company-id',
      uniqueId: 'user-123',           // Unique user identifier
      userName: 'John Doe',            // Optional
      userEmail: 'john@example.com',   // Optional
      debugMode: true,                 // Enable logs
    ),
  );

  runApp(MyApp());
}

2. Get Tickets #

final tickets = await iChatMode.tickets.getTickets();

// Include deleted tickets
final allTickets = await iChatMode.tickets.getTickets(includeDeleted: true);

3. Create Ticket #

final ticket = await iChatMode.tickets.createTicket(
  subject: 'Login Issue',
  message: 'Cannot access my account',
  priority: 'high',                    // critical, high, medium, low
  tags: ['login', 'urgent'],
  metadata: {'platform': 'mobile'},
  attachmentPaths: ['/path/to/screenshot.jpg'],
);

print('Ticket #${ticket.ticketNumber} created');

4. Get Ticket with Messages #

final result = await iChatMode.tickets.getTicketMessages(ticketId);

print('Ticket: ${result.ticket.subject}');
print('Messages: ${result.messages.length}');

5. Reply to Ticket #

await iChatMode.tickets.replyToTicket(
  ticketId: ticket.id,
  message: 'Thanks for your help!',
  attachmentPaths: ['/path/to/file.pdf'],
);

6. Real-time Updates #

// Listen for new tickets
iChatMode.tickets.onTicketCreated.listen((ticket) {
  print('New ticket: ${ticket.subject}');
});

// Listen for new messages
iChatMode.tickets.onMessageReceived.listen((message) {
  print('Message: ${message.content}');
});

// Listen for ticket updates
iChatMode.tickets.onTicketUpdated.listen((ticket) {
  print('Updated: ${ticket.statusLabel}');
});

// Listen for typing indicators
iChatMode.tickets.onTyping.listen((event) {
  print('${event['userName']} is typing...');
});

7. Join/Leave Ticket Room #

// Join ticket for real-time updates
await iChatMode.tickets.joinTicket(ticketId);

// Leave when done
await iChatMode.tickets.leaveTicket(ticketId);

8. Update Ticket Status #

await iChatMode.tickets.updateTicketStatus(
  ticketId: ticket.id,
  status: 'resolved',  // pending, open, resolved, closed
);

9. Reopen Ticket #

await iChatMode.tickets.reopenTicket(
  ticketId: ticket.id,
  reason: 'Issue not fully resolved',
  reopenedBy: 'Customer',
);

10. Typing Indicator #

await iChatMode.tickets.sendTypingIndicator(
  ticketId: ticket.id,
  isTyping: true,
);

Configuration #

iChatModeConfig Parameters #

Parameter Type Required Default Description
apiUrl String ✅ - Base API URL
apiKey String ✅ - API key
companyId String ✅ - Company ID
uniqueId String ✅ - Unique user ID
userName String ❌ null User name
userEmail String ❌ null User email
wsUrl String ❌ auto WebSocket URL
debugMode bool ❌ false Enable logs
maxFileSize int ❌ 25MB Max file size
allowedFileTypes List ❌ null Allowed MIME types

Advanced Configuration #

await iChatMode.initialize(
  config: iChatModeConfig(
    apiUrl: 'https://api.example.com/api',
    apiKey: 'tk_prod_key',
    companyId: 'mycompany',
    uniqueId: 'user-456',
    wsUrl: 'wss://ws.example.com/socket',
    debugMode: kDebugMode,
    maxFileSize: 10 * 1024 * 1024,  // 10MB
    allowedFileTypes: ['image/jpeg', 'image/png', 'application/pdf'],
  ),
);

File Attachments #

Validate Before Upload #

final errors = await iChatMode.tickets.validateAttachmentPaths([
  '/path/to/image.jpg',
  '/path/to/document.pdf',
]);

if (errors.isNotEmpty) {
  print('Error: ${errors.first}');
} else {
  // Proceed with upload
}

Supported Helper Methods #

// Get file extension
final ext = getFileExtension('/path/to/file.pdf');  // '.pdf'

// Format file size
final size = formatFileSize(1536000);  // '1.5 MB'

Models #

Ticket #

class Ticket {
  final String id;
  final String ticketNumber;
  final String subject;
  final String status;
  final String? priority;
  final List<String> tags;
  final DateTime createdAt;

  String get statusLabel;      // "Open", "Pending", "Resolved"
  String get priorityLabel;    // "Critical", "High", "Medium", "Low"
}

Message #

class Message {
  final String id;
  final String ticketId;
  final String content;
  final String senderId;
  final SenderType senderType;  // customer, agent, system
  final List<Attachment> attachments;
  final DateTime createdAt;
}

Attachment #

class Attachment {
  final String fileName;
  final String fileType;
  final int fileSize;
  final String url;

  String get extension;        // File extension
  String get formattedSize;    // Human-readable size
  bool get isImage;            // Check if image
}

Error Handling #

Exception Types #

try {
  await iChatMode.tickets.createTicket(/* ... */);
} on iChatValidationException catch (e) {
  print('Validation Error: ${e.message}');
} on iChatAuthException catch (e) {
  print('Auth Error: ${e.message}');
} on iChatNetworkException catch (e) {
  print('Network Error: ${e.message}');
} on iChatException catch (e) {
  print('SDK Error: ${e.message}');
}

User-Friendly Error Messages #

try {
  await iChatMode.tickets.getTickets();
} catch (e) {
  final message = normalizeErrorMessage(e);
  showSnackBar(message);  // Display to user
}

Push Notifications #

Setup Firebase #

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  await iChatMode.initialize(config: yourConfig);

  // Request permission
  await iChatMode.notifications.requestPermission();

  // Register device token
  await iChatMode.notifications.registerDevice();

  runApp(MyApp());
}

Handle Notification Taps #

FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  final ticketId = message.data['ticketId'];
  if (ticketId != null) {
    // Navigate to ticket chat
    Navigator.pushNamed(context, '/chat', arguments: ticketId);
  }
});

Real-time Events #

Available Streams #

Stream Type Description
onTicketCreated Stream<Ticket> New ticket created
onTicketUpdated Stream<Ticket> Ticket updated
onTicketDeleted Stream<String> Ticket deleted
onMessageReceived Stream<Message> New message
onMessageUpdated Stream<Message> Message edited
onMessageDeleted Stream<String> Message deleted
onTyping Stream<Map> Typing indicator

Dispose Subscriptions #

class MyScreen extends StatefulWidget {
  @override
  _MyScreenState createState() => _MyScreenState();
}

class _MyScreenState extends State<MyScreen> {
  StreamSubscription? _messageSub;

  @override
  void initState() {
    super.initState();
    _messageSub = iChatMode.tickets.onMessageReceived.listen(_handleMessage);
  }

  @override
  void dispose() {
    _messageSub?.cancel();
    super.dispose();
  }

  void _handleMessage(Message message) {
    // Handle message
  }
}

Best Practices #

1. Use State Management #

// With Provider
class TicketProvider extends ChangeNotifier {
  List<Ticket> tickets = [];
  bool isLoading = false;

  Future<void> loadTickets() async {
    isLoading = true;
    notifyListeners();

    tickets = await iChatMode.tickets.getTickets();

    isLoading = false;
    notifyListeners();
  }
}

2. Handle Loading States #

FutureBuilder<List<Ticket>>(
  future: iChatMode.tickets.getTickets(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return CircularProgressIndicator();
    }
    if (snapshot.hasError) {
      return Text('Error: ${snapshot.error}');
    }
    return TicketList(tickets: snapshot.data ?? []);
  },
)

3. Debounce Typing Indicator #

Timer? _typingTimer;

void _onTextChanged(String text) {
  _typingTimer?.cancel();

  iChatMode.tickets.sendTypingIndicator(
    ticketId: ticketId,
    isTyping: true,
  );

  _typingTimer = Timer(Duration(seconds: 3), () {
    iChatMode.tickets.sendTypingIndicator(
      ticketId: ticketId,
      isTyping: false,
    );
  });
}

4. Compress Images Before Upload #

import 'package:image/image.dart' as img;

Future<File> compressImage(File file) async {
  final bytes = await file.readAsBytes();
  final image = img.decodeImage(bytes);
  if (image == null) return file;

  final resized = img.copyResize(image, width: 1920);
  final compressed = img.encodeJpg(resized, quality: 85);

  final compressedFile = File('${file.path}_compressed.jpg');
  await compressedFile.writeAsBytes(compressed);
  return compressedFile;
}

Troubleshooting #

Common Issues #

WebSocket not connecting:

  • Check wsUrl format (ws:// or wss://)
  • Enable debugMode: true to see logs
  • Verify server supports WebSocket

Push notifications not working:

  • Verify Firebase setup (google-services.json)
  • Call requestPermission() and registerDevice()
  • Test with Firebase Console

File upload fails:

  • Check file size (maxFileSize limit)
  • Verify file type (allowedFileTypes)
  • Use validateAttachmentPaths() before upload

Real-time updates not working:

  • Call joinTicket(ticketId) before expecting updates
  • Verify WebSocket is connected (check debug logs)
  • Ensure subscriptions are not cancelled

API Summary #

Core Methods #

// Initialize
await iChatMode.initialize(config: iChatModeConfig(...));
await iChatMode.initializeWithDefaults();

// Tickets
await iChatMode.tickets.getTickets({includeDeleted: false});
await iChatMode.tickets.getTicketMessages(ticketId);
await iChatMode.tickets.createTicket(...);
await iChatMode.tickets.replyToTicket(...);
await iChatMode.tickets.updateTicketStatus(...);
await iChatMode.tickets.reopenTicket(...);

// Real-time
await iChatMode.tickets.joinTicket(ticketId);
await iChatMode.tickets.leaveTicket(ticketId);
await iChatMode.tickets.sendTypingIndicator(...);

// Validation
await iChatMode.tickets.validateAttachmentPaths(paths);

// Notifications
await iChatMode.notifications.requestPermission();
await iChatMode.notifications.registerDevice();
await iChatMode.notifications.getToken();

// Dispose
await iChatMode.instance.dispose();

Example #

See example/ directory for a complete working app.


Migration Guide #

From 1.0.3 to 1.0.4 #

New:

  • ticket.statusLabel - Human-readable status
  • ticket.priorityLabel - Human-readable priority
  • reopenTicket() - Reopen resolved tickets
  • validateAttachmentPaths() - Pre-upload validation

No breaking changes


License #

MIT License - see LICENSE file.


Support #


Built with ❤️ for Flutter developers

0
likes
140
points
57
downloads

Documentation

Documentation
API reference

Publisher

unverified uploader

Weekly Downloads

Official Flutter SDK for iChatMode ticket system. Logic-only SDK - no UI components. Build your own UI with your app's theme!

Repository (GitHub)

License

MIT (license)

Dependencies

connectivity_plus, firebase_core, firebase_messaging, flutter, flutter_image_compress, flutter_local_notifications, hive, hive_flutter, http, http_parser, image, intl, mime, path, path_provider, shared_preferences, timezone, uuid, web_socket_channel

More

Packages that depend on ichatmode_flutter_sdk