Flutter Chatbot SDK
dialogs_chatbot_flutter connects any iOS or Android Flutter app to an EnableX Dialogs
chatbot. At its centre is EnxChatController: it starts the chat engine, holds the
conversation state, and gives you methods to send messages plus callbacks and streams to receive them.
The chat protocol runs in a hidden WebView that the controller manages for you, and Dart talks to it
over a JavaScript bridge — no Swift or Kotlin code is needed. The controller is a
ChangeNotifier, so it fits Provider, Riverpod, BLoC, GetX or plain setState.
First release of the Flutter Chatbot SDK, published on pub.dev. See Release Notes for what's included.
View on pub.devThe same package also ships finished widgets — EnxChatScreen and EnxChatWidget — with theming and an in-app video call overlay. They are documented on the Flutter Chatbot UI Kit page. This page covers driving the chat from EnxChatController, for building your own interface or connecting the chat to your app's state.
Prerequisites
| Requirement | Value |
|---|---|
| Flutter | 3.10.0 or later |
| Dart | 3.0.0 or later (below 4.0.0) |
| iOS | 12.0 or later |
| Android | minSdkVersion 21 (Android 5.0), with Android System WebView 67 or later |
| Platforms | iOS and Android only |
Installation
Add Dependency
In the host app's pubspec.yaml. flutter_inappwebview and permission_handler must be declared directly in your app as well:
dependencies:
dialogs_chatbot_flutter: ^1.0.0
# Required in the host app
flutter_inappwebview: ^6.1.5
permission_handler: ^12.0.1
Run:
flutter pub get
All public types are exported from one file:
import 'package:dialogs_chatbot_flutter/dialogs_chatbot_flutter.dart';
iOS Setup
In ios/Runner/Info.plist, add:
<key>NSCameraUsageDescription</key>
<string>Camera access is required to send photos and make video calls.</string>
<key>NSMicrophoneUsageDescription</key>
<string>Microphone access is required for audio and video calls.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Photo library access is required to send images.</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>Photo library access is required to save images.</string>
In ios/Podfile, ensure minimum iOS version:
platform :ios, '12.0'
Android Setup
In android/app/src/main/AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- Android 13+ (API 33+) -->
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<!-- Android 12 and below -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="32" />
In android/app/build.gradle:
android {
defaultConfig {
minSdkVersion 21
}
}
Camera and microphone are needed for calls, the media permissions for sending photos and videos. See what each permission is for.
Pattern 1 — Controller with Your Own UI
Create an EnxChatController, set the callbacks you need, and call initialize(). The controller loads and manages its own hidden WebView, so you don't mount any plugin widget — render controller.messages however you like and call the send methods from your own input field. Because the controller is a ChangeNotifier, a ListenableBuilder rebuilds your UI whenever messages, typing or connection status change.
class MyChatPage extends StatefulWidget {
const MyChatPage({super.key});
@override
State<MyChatPage> createState() => _MyChatPageState();
}
class _MyChatPageState extends State<MyChatPage> {
late final EnxChatController _controller;
final _input = TextEditingController();
@override
void initState() {
super.initState();
_controller = EnxChatController(
config: const EnxBotConfig(
botId: 'YOUR_BOT_ID',
host: 'https://dialogs.enablex.io',
),
);
// Set callbacks before initialize()
_controller.onError = (message, type) => debugPrint('[$type] $message');
_controller.initialize();
}
@override
void dispose() {
_controller.dispose();
_input.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: _controller,
builder: (context, _) {
if (!_controller.isConnected) {
return const Center(child: CircularProgressIndicator());
}
return Column(
children: [
Expanded(
child: ListView(
children: [
for (final msg in _controller.messages)
if (!msg.hideInChat)
ListTile(
title: Text(msg.text ?? '[${msg.type.name}]'),
subtitle: Text(msg.sender.name),
),
if (_controller.isTyping) const ListTile(title: Text('Typing…')),
],
),
),
TextField(
controller: _input,
onSubmitted: (text) {
_controller.sendText(text);
_input.clear();
},
),
],
);
},
);
}
}
Call initialize() once, and always call dispose() when you're done — it closes the streams and releases the WebView.
Pattern 2 — BLoC / Stream Integration
If your app is built on streams, subscribe to messageStream and statusStream instead of (or as well as) using callbacks. Both are broadcast streams, so several listeners can subscribe, and both close when the controller is disposed.
// In your BLoC:
final _sub = controller.messageStream.listen(
(msg) => add(BotMessageEvent(msg)),
);
final _statusSub = controller.statusStream.listen(
(status) => add(ConnectionEvent(status)),
);
// In close / dispose:
await _sub.cancel();
await _statusSub.cancel();
controller.dispose();
Pattern 3 — Controller with the Ready-Made Widget
You can also hand your controller to the UI Kit's widget. You get the finished chat screen while keeping full access to the controller's state and methods elsewhere in your app.
@override
Widget build(BuildContext context) => EnxChatWidget.withController(
controller: _controller,
);
See Widget with your own controller on the UI Kit page.
Receiving Messages
Each message arrives as an EnxMessage — through onMessageReceived, messageStream and the messages list. Check message.type to decide how to render it; the content lives in different fields depending on the type.
controller.onMessageReceived = (EnxMessage msg) {
if (msg.hideInChat) return; // side-effect only, nothing to render
switch (msg.type) {
case EnxMessageType.text:
// msg.text — plain text
// msg.actions — optional action buttons
break;
case EnxMessageType.action:
// msg.actions — List<EnxAction> (title + url)
break;
case EnxMessageType.suggestion:
// msg.choices — List<EnxChoice>
// msg.suggestionType — single or multiple
break;
case EnxMessageType.image:
// msg.media?.url — CDN image URL
break;
case EnxMessageType.video:
// msg.media?.url — video URL
break;
case EnxMessageType.file:
// msg.media?.url, msg.media?.fileName, msg.media?.mimeType
break;
case EnxMessageType.system:
// msg.handoverStatus — handover lifecycle phase
break;
case EnxMessageType.typing:
// Typing indicator — also reflected in controller.isTyping
break;
default:
break;
}
};
See EnxMessage for every field.
Sending Messages
All send methods add the user's message to messages straight away (so your UI updates before the server confirms), then pass it through the bridge to the bot.
// Plain text
await controller.sendText('What are your hours?');
// One suggestion chip the user tapped
await controller.sendChoice(EnxChoice(title: 'Yes', value: 'yes'));
// Several chips from a multi-select suggestion
await controller.sendMultiChoice([
EnxChoice(title: 'Option A', value: 'a', isSelected: true),
EnxChoice(title: 'Option B', value: 'b', isSelected: true),
]);
// A file or image
final bytes = await File(path).readAsBytes();
await controller.sendFile(
bytes: bytes,
fileName: 'report.pdf',
mimeType: 'application/pdf',
);
// Start the conversation again (clears it on the server and locally)
await controller.resetConversation();
There is no offline queue. A message sent while the controller is not connected is not retried — check isConnected or watch statusStream and let the user retry.
Video Calls
A bot can start a live call with an agent. The call is a web page: the bot sends a message with audioVideoAction = "start" and an iFrameUrl, and later one with audioVideoAction = "stop". The controller tracks this for you:
- On
"start",activeVideoCallUrlis set to the call page URL and listeners are notified. - On
"stop", the controller callscloseVideoCallOverlay()andactiveVideoCallUrlreturns tonull.
The UI Kit widgets react to this automatically by opening and closing their call overlay — see Audio & Video Calling. If you render your own UI, watch activeVideoCallUrl and show the page yourself, for example in an InAppWebView from flutter_inappwebview with inline media playback allowed.
ListenableBuilder(
listenable: controller,
builder: (context, child) {
final url = controller.activeVideoCallUrl;
if (url == null) return child!;
return MyCallView(
url: url,
onClose: controller.closeVideoCallOverlay,
);
},
child: const MyChatView(),
)
For click-to-call bots (where the bot's clickToCall setting is "audio" or "video"), showClickToCallVideoOnlyUi is true — show a call-only screen instead of the chat, and call requestClickToCallVideo() to start the call.
Calls in the Flutter plugin always run from an iFrameUrl in a WebView; there is no native call path.
EnxBotConfig
Identifies the bot. Immutable and const-constructible; it is serialised with toJson() and sent to the chat engine on startup.
const EnxBotConfig({
required String botId,
required String host,
String rootPath = '',
bool callingEnabled = false,
})
| Field | Type | Required | Description |
|---|---|---|---|
botId | String | Yes | Bot identifier from the EnableX Dialogs dashboard. |
host | String | Yes | Base URL of the Dialogs backend, for example https://dialogs.enablex.io. |
rootPath | String | No | Optional URL path prefix appended to host. Default ''. |
callingEnabled | bool | No | Shows the call buttons in the UI Kit's input bar. Default false. |
EnxChatController
The central state manager. It extends ChangeNotifier and calls notifyListeners() on every change, owns the JavaScript bridge, and exposes the conversation through properties, streams and callbacks.
EnxChatController({required EnxBotConfig config})
Lifecycle
| Method | Description |
|---|---|
Future<void> initialize() | Loads the bridge WebView and starts connecting. Call once, typically in initState, after setting callbacks. |
void dispose() | Closes the streams and releases the WebView. Call in your dispose(). |
Future<void> reconnect() | Manually retries the socket connection, for example after error. |
Future<void> resetConversation() | Clears the conversation on the server and the local message list. |
void clearMessages() | Clears the local message list only; the server conversation is untouched. |
State (read-only)
| Property | Type | Description |
|---|---|---|
messages | List<EnxMessage> | All messages, oldest first. |
status | EnxConnectionStatus | Current connection state. |
isConnected | bool | true when status is connected. |
isTyping | bool | true while the bot is typing. |
botInfo | Map<String, dynamic>? | Bot metadata from the server. |
hasReceivedBotInfo | bool | Whether bot metadata has arrived yet. |
conversationId | String? | Identifier of the active conversation. |
errorMessage | String? | The last error message. |
activeVideoCallUrl | String? | The call page URL while a call is active; otherwise null. |
showClickToCallVideoOnlyUi | bool | true when the bot's clickToCall mode is anything other than "text". |
Send methods
| Method | Description |
|---|---|
Future<void> sendText(String text) | Sends a plain-text message. |
Future<void> sendChoice(EnxChoice choice) | Sends one selected suggestion chip. |
Future<void> sendMultiChoice(List<EnxChoice> choices) | Sends several selected chips. |
Future<void> sendSuggestions(List<String> titles, EnxSuggestionType type) | Sends suggestion titles. |
Future<void> sendFile({required List<int> bytes, required String fileName, required String mimeType}) | Uploads and sends a file or image. |
Future<void> sendRawBytes(List<int> bytes, String fileName) | Sends raw file bytes. |
Call methods
| Method | Description |
|---|---|
Future<void> requestClickToCallVideo() | Starts click-to-call video mode. |
void closeVideoCallOverlay() | Ends the in-app call view: sets activeVideoCallUrl to null and notifies listeners. |
Streams
| Stream | Emits |
|---|---|
Stream<EnxMessage> messageStream | Each new message as it arrives — the same data as onMessageReceived. |
Stream<EnxConnectionStatus> statusStream | Every connection status change. |
Both are broadcast streams (multiple listeners allowed) and close when dispose() is called.
controller.statusStream
.where((s) => s == EnxConnectionStatus.error)
.listen((_) => _showReconnectDialog());
Controller Callbacks
Assign these properties before calling initialize(). Each is optional.
controller.onMessageReceived = (EnxMessage msg) { ... };
controller.onStatusChanged = (EnxConnectionStatus status) { ... };
controller.onError = (String message, String type) { ... };
controller.onBotInfoReceived = (Map<String, dynamic> info) { ... };
onMessageReceived
Fires when a message is added to the conversation — a bot reply, a typing indicator or a user-message echo. Receives the EnxMessage. Do: render it, or ignore it if hideInChat is true.
onStatusChanged
Fires when the connection state changes. Receives an EnxConnectionStatus. Suggested handling:
| Status | Meaning | Suggested UI |
|---|---|---|
idle | Not started yet | Empty state |
loading | WebView and bridge loading | Spinner |
connected | Socket ready, chat active | Chat UI |
disconnected | Socket dropped | “Disconnected” banner |
reconnecting | Automatic reconnect in progress | “Reconnecting…” |
error | Unrecoverable error | Error state with a retry button that calls reconnect() |
onError
Fires when the bridge, socket or an upload reports an error. Receives a human-readable message and a machine-readable type:
type | Description |
|---|---|
socket_error | WebSocket connection error |
send_error | A message failed to send |
file_upload_error | A file upload failed |
bridge_error | JS ↔ Dart bridge communication error |
unknown_error | Unclassified error |
controller.onError = (String message, String type) {
logger.e('[$type] $message');
if (type == 'file_upload_error') {
showDialog(/* upload failed */);
}
};
onBotInfoReceived
Fires when the server sends the bot's metadata after connecting. Receives a Map<String, dynamic>; the exact keys depend on how the bot is set up in the Dialogs dashboard. Common keys:
| Key | Type | Description |
|---|---|---|
name | String | Bot display name |
avatar | String? | Bot avatar image URL |
welcomeMessage | String? | Initial greeting |
settings | Map? | Other server-defined settings |
controller.onBotInfoReceived = (info) {
setState(() {
_botName = info['name'] as String? ?? 'Assistant';
_botAvatar = info['avatar'] as String?;
});
};
The UI Kit widgets accept the same callbacks as constructor parameters, plus onMessageSent, onAudioCall and onVideoCall. See Listening to chat events.
EnxMessage
One message in the conversation, from the user or the bot.
| Property | Type | Description |
|---|---|---|
id | String? | Server-assigned ID; null for local messages. |
sender | EnxMessageSender | user or bot. |
type | EnxMessageType | Content type (see below). |
timestamp | DateTime | When the message was created. |
text | String? | Text content; null for media messages. |
subtitle | String? | Secondary text below the title. |
media | EnxMedia? | Attached image, video or file. |
choices | List<EnxChoice>? | Suggestion chips. |
actions | List<EnxAction>? | Action link buttons. |
suggestionType | EnxSuggestionType? | single or multiple. |
handoverStatus | String? | Live-agent handover phase, for example "transfer_initiated". |
audioVideoAction | String? | "start" or "stop" for a call. |
iFrameUrl | String? | Call page URL. |
hideInChat | bool | When true, the message exists only for its side effects and should not be rendered. |
EnxMessageType
| Value | Description |
|---|---|
text | Plain text, with optional action buttons |
action | One or more URL action buttons |
suggestion | Tappable suggestion chips |
image | Image card from a URL |
file | Downloadable file attachment |
video | Video |
typing | Bot typing indicator |
calendar | Date prompt — rendered as text in v1.0.0; a date picker is planned |
system | System or handover status message |
Factory constructors
Used to build outgoing user messages:
EnxMessage.userText('Hello!')
EnxMessage.userMedia(
bytes: imageBytes,
fileName: 'photo.jpg',
mimeType: 'image/jpeg',
)
EnxMessage.userFile(
bytes: pdfBytes,
fileName: 'document.pdf',
mimeType: 'application/pdf',
)
Sub-models
EnxChoice
| Property | Type | Description |
|---|---|---|
title | String | Label shown on the chip |
value | String | Value sent to the bot when selected |
isSelected | bool | Local selection state, mutable for multi-select |
EnxAction
| Property | Type | Description |
|---|---|---|
title | String | Button label |
url | String? | URL opened in the browser on tap |
action | String? | Action type, for example 'url' |
EnxMedia
| Property | Type | Description |
|---|---|---|
url | String? | CDN URL for media sent by the bot |
fileName | String | File name with extension |
mimeType | String | MIME type, for example image/png |
localBytes | List<int>? | Raw bytes before upload |
size | int? | File size in bytes |
isImage / isVideo / isPdf | bool | Convenience checks on the MIME type |
Enums
| Enum | Values |
|---|---|
EnxConnectionStatus | idle, loading, connected, disconnected, reconnecting, error — see onStatusChanged and the state machine |
EnxMessageSender | user, bot |
EnxSuggestionType | single (tapping one chip sends immediately), multiple (the user picks several, then confirms) |
Plugin Architecture
EnxChatController owns an EnxWebViewBridge. The bridge loads assets/chat/chat.html into a hidden 1×1 WebView, sends it the bot config with postMessage, and from then on the page runs the chat protocol and the Socket.IO connection. The page reports events back to Dart over a JavaScript channel, and Dart sends it commands by running JavaScript.
Startup & messaging sequence
Connection state machine
How EnxConnectionStatus moves between states. statusStream and onStatusChanged report every transition.
dispose(). From error, call reconnect() to try again.JS Bridge Communication
The bridge uses a JavaScript channel named EnxChannel. Every message from the page is a JSON string with an event name and optional data:
{
"event": "message",
"data": {
...
}
}
Events received from JS
| Event | Data | Description |
|---|---|---|
chatReady | — | HTML fully loaded |
connected | — | Socket connected |
disconnected | — | Socket dropped |
reconnecting | — | Auto-reconnect started |
reconnected | — | Reconnect succeeded |
reconnectFailed | — | Reconnect attempts exhausted |
botInfo | Map<String, dynamic> | Bot metadata |
conversationReady | { conversationId: string } | Conversation initialised |
message | Array<MessageObject> | One or more messages |
typing | { duration: number } | Typing indicator |
clear | { conversationId?: string } | Conversation cleared |
messageSent | — | User message confirmed by server |
fileSent | — | File upload confirmed |
error | { message: string, type: string } | Error from JS |
Commands sent to JS
window.sendTextMessage(text)
window.sendSuggestion(value)
window.sendMultiSuggestions([value1, value2])
window.sendFileMessage(base64DataURI, fileName, mimeType)
window.resetConversation()
window.reconnect()
window.disconnect()
These are internal to the plugin — use the controller's methods rather than calling them yourself.
Platform-Specific WebView Setup
The plugin configures its WebViews for inline media automatically (in enx_webview_media_config.dart); you don't need to call anything.
Android
PlatformWebViewControllerCreationParams enxWebViewCreationParamsForMedia()
// Returns AndroidWebViewControllerCreationParams with:
// - allowFileAccess: true
// - javaScriptCanOpenWindowsAutomatically: true
void enxConfigureAndroidWebViewMediaPermissions(WebViewController controller)
// Configures:
// - mediaPlaybackRequiresUserGesture: false
// - onPermissionRequest: auto-grant camera/mic
iOS
// Returns WebKitWebViewControllerCreationParams with:
// - allowsInlineMediaPlayback: true
// - mediaTypesRequiringUserActionForPlayback: []
On Android the WebView grants camera and microphone to the page automatically, but only after the app itself holds those permissions. The plugin requests them at runtime with permission_handler before a call begins.
Security Model
- No native platform channels carry chat data — the protocol runs in JavaScript inside the WebView sandbox.
botIdandhostare passed to the page at runtime, not compiled into the page.- File uploads go directly from the WebView to the EnableX CDN over HTTPS.
- The call view is a separate
InAppWebViewinstance with no DOM access to the chat WebView.
File Structure
lib/
├── dialogs_chatbot_flutter.dart ← Single import barrel
└── src/
├── models/
│ ├── enx_bot_config.dart ← Bot configuration data object
│ └── enx_message.dart ← All message models + enums
├── controller/
│ └── enx_chat_controller.dart ← State, streams, send methods
├── bridge/
│ └── enx_webview_bridge.dart ← JS↔Dart bridge
├── utils/
│ └── enx_webview_media_config.dart ← Platform WebView config
└── views/ ← UI Kit widgets
├── enx_chat_widget.dart ← Embeddable widget
├── enx_chat_screen.dart ← Full-screen scaffold
├── enx_chat_list.dart ← Scrollable message list
├── enx_message_cell.dart ← Per-message renderer + theme
├── enx_input_bar.dart ← Input + attachments + call buttons
├── enx_typing_bubble.dart ← Animated 3-dot indicator
└── enx_video_call_overlay.dart ← Agent video WebView (InAppWebView)
assets/
└── chat/
└── chat.html ← Bundled JS chat runtime
Feature Support (v1.0.0)
| Feature | Supported | Notes |
|---|---|---|
| Controller without plugin widgets | Yes | EnxChatController manages its own hidden WebView. |
| Framework-agnostic state management | Yes | ChangeNotifier; works with Provider, Riverpod, BLoC, GetX or setState. |
| Reactive streams | Yes | messageStream / statusStream. |
| Text, actions, suggestion chips (single/multi) | Yes | |
| Image / video / file messages | Yes | Receive via EnxMedia; send with sendFile. |
| System / handover messages | Yes | handoverStatus on system messages. |
| Video call state | Yes | activeVideoCallUrl, closeVideoCallOverlay(); calls run from an iFrameUrl. |
| Click-to-call (text / audio / video) | Yes | Server-driven via botInfo.clickToCall; exposed as showClickToCallVideoOnlyUi. |
| Conversation reset / manual reconnect | Yes | resetConversation(), reconnect(). |
| Ready-made chat UI | Yes | See the Flutter Chatbot UI Kit. |
| Calendar (date picker) prompts | No | calendar messages render as text in v1.0.0; planned. |
| Native (token-based) calls | No | Calls always load an iFrameUrl in a WebView. |
| Offline message queue | No | Watch statusStream and prompt the user to retry. |
| Web / desktop targets | No | iOS and Android only — use the Web Chatbot SDK for web. |
Dependencies
| Package | Version | License | Purpose |
|---|---|---|---|
webview_flutter | ^4.13.0 | BSD-3 | Chat bridge WebView |
flutter_inappwebview | ^6.1.5 | Apache-2.0 | Video call WebView |
image_picker | ^1.2.0 | BSD-3 | Camera/gallery |
file_picker | ^11.0.2 | MIT | Document picker |
permission_handler | ^12.0.1 | MIT | Runtime permissions |
cached_network_image | ^3.4.0 | MIT | Image caching |
video_player | ^2.11.0 | BSD-3 | Inline video |
url_launcher | ^6.3.0 | BSD-3 | Open action URLs |
http | ^1.6.0 | BSD-3 | HTTP requests |
mime | ^2.0.0 | BSD-3 | MIME detection |
intl | ^0.20.2 | BSD-3 | Date formatting |
Known Limitations
| Limitation | Impact | Workaround |
|---|---|---|
| iOS & Android only | Web/Desktop not supported | Use the Web Chatbot SDK for web |
flutter_inappwebview and permission_handler must be direct dependencies | Host app must add them | Add both to the host pubspec.yaml |
| Calendar message type not yet implemented | EnxMessageType.calendar renders as text | Planned for v1.1.0 |
| No offline queue | Messages fail silently when disconnected | Monitor statusStream and prompt retry |
| Browser calls only | No native call path | Start native calls from your own calling SDK |
| Android WebView version | Requires Android System WebView 67+ | Advise users to update |
Troubleshooting
Status never reaches connected
- Check that
botIdandhostare correct. - Confirm network connectivity to
host. - Set
onErrorbeforeinitialize()and look forbridge_errororsocket_error.
Images/videos don't autoplay on Android
- The plugin configures the WebView for this automatically (
enxConfigureAndroidWebViewMediaPermissions). - Check that
minSdkVersionis at least 21 and Android System WebView is up to date.
MissingPluginException for flutter_inappwebview
- Add
flutter_inappwebview: ^6.1.5andpermission_handlerto the host app'spubspec.yaml. - Run
flutter pub getand do a full rebuild.
File upload fails on iOS
- Add all the
NS*UsageDescriptionkeys toInfo.plist. - Request permissions before calling
sendFile. - Check
onErrorforfile_upload_error.
Black screen in the call view
- Confirm the
iFrameUrlis HTTPS. - Add an
NSAppTransportSecurityexception if needed for development.
License
This plugin is proprietary software owned by EnableX / VCloudX Infotech. All rights reserved. Redistribution requires written permission.
Support
- Dashboard: portal.enablex.io
- Docs: developer.enablex.io
- Issues: Contact EnableX support team