ichatmode_flutter_sdk 1.0.5
ichatmode_flutter_sdk: ^1.0.5 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!
example/lib/main.dart
import 'package:flutter/material.dart';
import 'package:ichatmode_flutter_sdk/ichatmode_flutter_sdk.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialize iChatMode SDK
await iChatMode.initialize(
config: iChatModeConfig(
apiUrl: 'https://your-api.com', // Replace with your API URL
apiKey: 'your-api-key', // Replace with your API key
companyId: 'your-company-id', // Replace with your company ID
userName: 'Demo User',
userEmail: 'demo@example.com',
debugMode: true, // Enable for development
enableOfflineMode: true,
enablePushNotifications: false, // Set to true if Firebase is configured
),
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'iChatMode Example',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: TicketListScreen(),
);
}
}
class TicketListScreen extends StatefulWidget {
@override
_TicketListScreenState createState() => _TicketListScreenState();
}
class _TicketListScreenState extends State<TicketListScreen> {
List<Ticket> tickets = [];
bool loading = true;
String? error;
@override
void initState() {
super.initState();
_loadTickets();
_listenToUpdates();
}
void _loadTickets() async {
try {
setState(() {
loading = true;
error = null;
});
final fetchedTickets = await iChatMode.tickets.getTickets();
setState(() {
tickets = fetchedTickets;
loading = false;
});
} catch (e) {
setState(() {
error = e.toString();
loading = false;
});
}
}
void _listenToUpdates() {
// Listen for new tickets
iChatMode.tickets.onTicketCreated.listen((ticket) {
setState(() {
tickets.insert(0, ticket);
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('New ticket created: ${ticket.subject}')),
);
});
// 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) {
return Scaffold(
appBar: AppBar(
title: Text('Support Tickets'),
actions: [
IconButton(
icon: Icon(Icons.refresh),
onPressed: _loadTickets,
),
],
),
body: _buildBody(),
floatingActionButton: FloatingActionButton(
onPressed: _showCreateTicketDialog,
child: Icon(Icons.add),
tooltip: 'Create Ticket',
),
);
}
Widget _buildBody() {
if (loading) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
SizedBox(height: 16),
Text('Loading tickets...'),
],
),
);
}
if (error != null) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.error_outline, size: 64, color: Colors.red),
SizedBox(height: 16),
Text('Error loading tickets:', style: TextStyle(fontSize: 18)),
SizedBox(height: 8),
Text(error!, textAlign: TextAlign.center),
SizedBox(height: 16),
ElevatedButton(
onPressed: _loadTickets,
child: Text('Retry'),
),
],
),
);
}
if (tickets.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.inbox, size: 64, color: Colors.grey),
SizedBox(height: 16),
Text('No tickets yet', style: TextStyle(fontSize: 18)),
SizedBox(height: 8),
Text('Create your first support ticket'),
],
),
);
}
return RefreshIndicator(
onRefresh: () async => _loadTickets(),
child: ListView.builder(
itemCount: tickets.length,
itemBuilder: (context, index) {
final ticket = tickets[index];
return _buildTicketCard(ticket);
},
),
);
}
Widget _buildTicketCard(Ticket ticket) {
return Card(
margin: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: ListTile(
title: Text(
ticket.subject,
style: TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 4),
Row(
children: [
_buildStatusChip(ticket.status),
SizedBox(width: 8),
_buildPriorityChip(ticket.priority),
],
),
SizedBox(height: 4),
Text(
'Created: ${_formatDate(ticket.createdAt)}',
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
),
if (ticket.messageCount > 0)
Text(
'${ticket.messageCount} messages',
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
),
],
),
trailing: Icon(Icons.chevron_right),
onTap: () => _openTicket(ticket),
),
);
}
Widget _buildStatusChip(String status) {
Color color;
switch (status.toLowerCase()) {
case 'open':
color = Colors.green;
break;
case 'closed':
color = Colors.grey;
break;
case 'in_progress':
color = Colors.blue;
break;
default:
color = Colors.orange;
}
return Chip(
label: Text(
status.toUpperCase(),
style: TextStyle(color: Colors.white, fontSize: 10),
),
backgroundColor: color,
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
);
}
Widget _buildPriorityChip(String priority) {
Color color;
switch (priority.toLowerCase()) {
case 'high':
color = Colors.red;
break;
case 'medium':
color = Colors.orange;
break;
case 'low':
color = Colors.green;
break;
default:
color = Colors.grey;
}
return Chip(
label: Text(
priority.toUpperCase(),
style: TextStyle(color: Colors.white, fontSize: 10),
),
backgroundColor: color,
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
);
}
String _formatDate(DateTime date) {
final now = DateTime.now();
final difference = now.difference(date);
if (difference.inDays > 0) {
return '${difference.inDays}d ago';
} else if (difference.inHours > 0) {
return '${difference.inHours}h ago';
} else if (difference.inMinutes > 0) {
return '${difference.inMinutes}m ago';
} else {
return 'Just now';
}
}
void _openTicket(Ticket ticket) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TicketChatScreen(ticket: ticket),
),
);
}
void _showCreateTicketDialog() {
final subjectController = TextEditingController();
final messageController = TextEditingController();
String priority = 'medium';
showDialog(
context: context,
builder: (context) => StatefulBuilder(
builder: (context, setState) => AlertDialog(
title: Text('Create Support Ticket'),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: subjectController,
decoration: InputDecoration(
labelText: 'Subject',
border: OutlineInputBorder(),
),
),
SizedBox(height: 16),
TextField(
controller: messageController,
decoration: InputDecoration(
labelText: 'Message',
border: OutlineInputBorder(),
),
maxLines: 3,
),
SizedBox(height: 16),
DropdownButtonFormField<String>(
value: priority,
decoration: InputDecoration(
labelText: 'Priority',
border: OutlineInputBorder(),
),
items: ['low', 'medium', 'high', 'critical']
.map((p) => DropdownMenuItem(
value: p,
child: Text(p.toUpperCase()),
))
.toList(),
onChanged: (value) => setState(() => priority = value!),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text('Cancel'),
),
ElevatedButton(
onPressed: () => _createTicket(
subjectController.text,
messageController.text,
priority,
),
child: Text('Create'),
),
],
),
),
);
}
void _createTicket(String subject, String message, String priority) async {
if (subject.trim().isEmpty || message.trim().isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Please fill in all fields')),
);
return;
}
Navigator.pop(context); // Close dialog
try {
final ticket = await iChatMode.tickets.createTicket(
subject: subject.trim(),
message: message.trim(),
priority: priority,
tags: ['mobile_app'],
metadata: {'created_from': 'example_app'},
);
setState(() {
tickets.insert(0, ticket);
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Ticket created successfully!')),
);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error creating ticket: $e')),
);
}
}
}
class TicketChatScreen extends StatefulWidget {
final Ticket ticket;
TicketChatScreen({required this.ticket});
@override
_TicketChatScreenState createState() => _TicketChatScreenState();
}
class _TicketChatScreenState extends State<TicketChatScreen> {
List<Message> messages = [];
bool loading = true;
final messageController = TextEditingController();
final scrollController = ScrollController();
Map<String, String> typingUsers = {};
@override
void initState() {
super.initState();
_loadMessages();
_joinChat();
_listenToMessages();
}
void _loadMessages() async {
try {
final result = await iChatMode.tickets.getTicketMessages(widget.ticket.id);
setState(() {
messages = result.messages;
loading = false;
});
_scrollToBottom();
} catch (e) {
setState(() => loading = false);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error loading messages: $e')),
);
}
}
void _joinChat() {
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);
});
_scrollToBottom();
}
});
// Listen for typing updates
iChatMode.tickets.onTypingUpdate.listen((update) {
if (update.ticketId == widget.ticket.id) {
setState(() {
typingUsers = update.users;
});
}
});
}
void _scrollToBottom() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (scrollController.hasClients) {
scrollController.animateTo(
scrollController.position.maxScrollExtent,
duration: Duration(milliseconds: 300),
curve: Curves.easeOut,
);
}
});
}
void _sendMessage() async {
final text = messageController.text.trim();
if (text.isEmpty) return;
messageController.clear();
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() {
iChatMode.tickets.leaveTicketChat(widget.ticket.id);
messageController.dispose();
scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(widget.ticket.subject),
Text(
'Status: ${widget.ticket.status}',
style: TextStyle(fontSize: 12),
),
],
),
),
body: Column(
children: [
Expanded(
child: loading
? Center(child: CircularProgressIndicator())
: ListView.builder(
controller: scrollController,
itemCount: messages.length,
itemBuilder: (context, index) {
final message = messages[index];
return MessageBubble(message: message);
},
),
),
if (typingUsers.isNotEmpty) _buildTypingIndicator(),
_buildMessageInput(),
],
),
);
}
Widget _buildTypingIndicator() {
final names = typingUsers.values.toList();
String text;
if (names.length == 1) {
text = '${names[0]} is typing...';
} else if (names.length == 2) {
text = '${names[0]} and ${names[1]} are typing...';
} else {
text = '${names.length} people are typing...';
}
return Container(
padding: EdgeInsets.all(8),
child: Text(
text,
style: TextStyle(
fontStyle: FontStyle.italic,
color: Colors.grey[600],
),
),
);
}
Widget _buildMessageInput() {
return Container(
padding: EdgeInsets.all(8),
decoration: BoxDecoration(
border: Border(top: BorderSide(color: Colors.grey[300]!)),
),
child: Row(
children: [
Expanded(
child: TextField(
controller: messageController,
decoration: InputDecoration(
hintText: 'Type a message...',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
),
contentPadding: EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
),
onChanged: (text) {
// Send typing indicator
iChatMode.tickets.sendTypingIndicator(
widget.ticket.id,
text.isNotEmpty,
);
},
onSubmitted: (_) => _sendMessage(),
),
),
SizedBox(width: 8),
IconButton(
onPressed: _sendMessage,
icon: Icon(Icons.send),
color: Theme.of(context).primaryColor,
),
],
),
);
}
}
class MessageBubble extends StatelessWidget {
final Message message;
MessageBubble({required this.message});
@override
Widget build(BuildContext context) {
final isUser = message.isFromUser;
return Container(
margin: EdgeInsets.symmetric(vertical: 4, horizontal: 8),
child: Row(
mainAxisAlignment: isUser ? MainAxisAlignment.end : MainAxisAlignment.start,
children: [
if (!isUser) _buildAvatar(),
Flexible(
child: Container(
margin: EdgeInsets.symmetric(horizontal: 8),
padding: EdgeInsets.all(12),
decoration: BoxDecoration(
color: isUser ? Colors.blue : Colors.grey[200],
borderRadius: BorderRadius.circular(16),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (!isUser && message.senderName != null)
Text(
message.senderName!,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 12,
color: Colors.grey[600],
),
),
if (message.content.isNotEmpty)
Text(
message.content,
style: TextStyle(
color: isUser ? Colors.white : Colors.black,
),
),
if (message.hasAttachments) ..._buildAttachments(),
SizedBox(height: 4),
Text(
_formatTime(message.createdAt),
style: TextStyle(
fontSize: 10,
color: isUser ? Colors.white70 : Colors.grey[600],
),
),
],
),
),
),
if (isUser) _buildAvatar(),
],
),
);
}
Widget _buildAvatar() {
return CircleAvatar(
radius: 16,
backgroundColor: message.isFromUser ? Colors.blue : Colors.grey,
child: Text(
message.isFromUser ? 'U' : 'A',
style: TextStyle(color: Colors.white, fontSize: 12),
),
);
}
List<Widget> _buildAttachments() {
return message.attachments.map((attachment) {
return Container(
margin: EdgeInsets.only(top: 8),
padding: EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.black12,
borderRadius: BorderRadius.circular(8),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
attachment.isImage ? Icons.image : Icons.attach_file,
size: 16,
),
SizedBox(width: 4),
Flexible(
child: Text(
attachment.originalName,
style: TextStyle(fontSize: 12),
overflow: TextOverflow.ellipsis,
),
),
],
),
);
}).toList();
}
String _formatTime(DateTime dateTime) {
final now = DateTime.now();
final today = DateTime(now.year, now.month, now.day);
final messageDate = DateTime(dateTime.year, dateTime.month, dateTime.day);
if (messageDate == today) {
return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
} else {
return '${dateTime.day}/${dateTime.month} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
}
}
}