Flutter Chatbot SDK

View Release Notes →

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.

Flutter Chatbot SDK v1.0.0  ·  Released June 25, 2026

First release of the Flutter Chatbot SDK, published on pub.dev. See Release Notes for what's included.

  View on pub.dev
Want a ready-made chat screen?

The 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.

Setup

Prerequisites

RequirementValue
Flutter3.10.0 or later
Dart3.0.0 or later (below 4.0.0)
iOS12.0 or later
AndroidminSdkVersion 21 (Android 5.0), with Android System WebView 67 or later
PlatformsiOS 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.

Usage Patterns

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.

Handling Messages

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", activeVideoCallUrl is set to the call page URL and listeners are notified.
  • On "stop", the controller calls closeVideoCallOverlay() and activeVideoCallUrl returns to null.

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.

API Reference

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,
})
FieldTypeRequiredDescription
botIdStringYesBot identifier from the EnableX Dialogs dashboard.
hostStringYesBase URL of the Dialogs backend, for example https://dialogs.enablex.io.
rootPathStringNoOptional URL path prefix appended to host. Default ''.
callingEnabledboolNoShows 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

MethodDescription
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)

PropertyTypeDescription
messagesList<EnxMessage>All messages, oldest first.
statusEnxConnectionStatusCurrent connection state.
isConnectedbooltrue when status is connected.
isTypingbooltrue while the bot is typing.
botInfoMap<String, dynamic>?Bot metadata from the server.
hasReceivedBotInfoboolWhether bot metadata has arrived yet.
conversationIdString?Identifier of the active conversation.
errorMessageString?The last error message.
activeVideoCallUrlString?The call page URL while a call is active; otherwise null.
showClickToCallVideoOnlyUibooltrue when the bot's clickToCall mode is anything other than "text".

Send methods

MethodDescription
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

MethodDescription
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

StreamEmits
Stream<EnxMessage> messageStreamEach new message as it arrives — the same data as onMessageReceived.
Stream<EnxConnectionStatus> statusStreamEvery 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:

StatusMeaningSuggested UI
idleNot started yetEmpty state
loadingWebView and bridge loadingSpinner
connectedSocket ready, chat activeChat UI
disconnectedSocket dropped“Disconnected” banner
reconnectingAutomatic reconnect in progress“Reconnecting…”
errorUnrecoverable errorError 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:

typeDescription
socket_errorWebSocket connection error
send_errorA message failed to send
file_upload_errorA file upload failed
bridge_errorJS ↔ Dart bridge communication error
unknown_errorUnclassified 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:

KeyTypeDescription
nameStringBot display name
avatarString?Bot avatar image URL
welcomeMessageString?Initial greeting
settingsMap?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.

PropertyTypeDescription
idString?Server-assigned ID; null for local messages.
senderEnxMessageSenderuser or bot.
typeEnxMessageTypeContent type (see below).
timestampDateTimeWhen the message was created.
textString?Text content; null for media messages.
subtitleString?Secondary text below the title.
mediaEnxMedia?Attached image, video or file.
choicesList<EnxChoice>?Suggestion chips.
actionsList<EnxAction>?Action link buttons.
suggestionTypeEnxSuggestionType?single or multiple.
handoverStatusString?Live-agent handover phase, for example "transfer_initiated".
audioVideoActionString?"start" or "stop" for a call.
iFrameUrlString?Call page URL.
hideInChatboolWhen true, the message exists only for its side effects and should not be rendered.

EnxMessageType

ValueDescription
textPlain text, with optional action buttons
actionOne or more URL action buttons
suggestionTappable suggestion chips
imageImage card from a URL
fileDownloadable file attachment
videoVideo
typingBot typing indicator
calendarDate prompt — rendered as text in v1.0.0; a date picker is planned
systemSystem 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

PropertyTypeDescription
titleStringLabel shown on the chip
valueStringValue sent to the bot when selected
isSelectedboolLocal selection state, mutable for multi-select

EnxAction

PropertyTypeDescription
titleStringButton label
urlString?URL opened in the browser on tap
actionString?Action type, for example 'url'

EnxMedia

PropertyTypeDescription
urlString?CDN URL for media sent by the bot
fileNameStringFile name with extension
mimeTypeStringMIME type, for example image/png
localBytesList<int>?Raw bytes before upload
sizeint?File size in bytes
isImage / isVideo / isPdfboolConvenience checks on the MIME type

Enums

EnumValues
EnxConnectionStatusidle, loading, connected, disconnected, reconnecting, error — see onStatusChanged and the state machine
EnxMessageSenderuser, bot
EnxSuggestionTypesingle (tapping one chip sends immediately), multiple (the user picks several, then confirms)
Architecture

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.

Layered architecture: your Flutter app, the UI layer widgets, EnxChatController, EnxWebViewBridge and the hidden chat WebView connected to the EnableX Dialogs server, plus the call overlay that loads the agent call page.
Green = the plugin, purple = the hidden chat WebView, blue = your app and remote services. The UI layer is optional when you drive the controller yourself.

Startup & messaging sequence

Sequence diagram of controller initialization, WebView handshake, connection, bot info, and a message round trip with typing indicator.
Solid arrows are calls; dashed arrows are events coming back from the WebView or server.

Connection state machine

How EnxConnectionStatus moves between states. statusStream and onStatusChanged report every transition.

State diagram: idle to loading on initialize; loading to connected or error; connected to disconnected when the socket drops; disconnected to reconnecting or error; reconnecting to connected or error; error to loading on reconnect(); dispose returns to idle.
Dashed arrows are 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

EventDataDescription
chatReady—HTML fully loaded
connected—Socket connected
disconnected—Socket dropped
reconnecting—Auto-reconnect started
reconnected—Reconnect succeeded
reconnectFailed—Reconnect attempts exhausted
botInfoMap<String, dynamic>Bot metadata
conversationReady{ conversationId: string }Conversation initialised
messageArray<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.
  • botId and host are 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 InAppWebView instance 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

Feature Support (v1.0.0)

FeatureSupportedNotes
Controller without plugin widgetsYesEnxChatController manages its own hidden WebView.
Framework-agnostic state managementYesChangeNotifier; works with Provider, Riverpod, BLoC, GetX or setState.
Reactive streamsYesmessageStream / statusStream.
Text, actions, suggestion chips (single/multi)Yes
Image / video / file messagesYesReceive via EnxMedia; send with sendFile.
System / handover messagesYeshandoverStatus on system messages.
Video call stateYesactiveVideoCallUrl, closeVideoCallOverlay(); calls run from an iFrameUrl.
Click-to-call (text / audio / video)YesServer-driven via botInfo.clickToCall; exposed as showClickToCallVideoOnlyUi.
Conversation reset / manual reconnectYesresetConversation(), reconnect().
Ready-made chat UIYesSee the Flutter Chatbot UI Kit.
Calendar (date picker) promptsNocalendar messages render as text in v1.0.0; planned.
Native (token-based) callsNoCalls always load an iFrameUrl in a WebView.
Offline message queueNoWatch statusStream and prompt the user to retry.
Web / desktop targetsNoiOS and Android only — use the Web Chatbot SDK for web.
Reference

Dependencies

PackageVersionLicensePurpose
webview_flutter^4.13.0BSD-3Chat bridge WebView
flutter_inappwebview^6.1.5Apache-2.0Video call WebView
image_picker^1.2.0BSD-3Camera/gallery
file_picker^11.0.2MITDocument picker
permission_handler^12.0.1MITRuntime permissions
cached_network_image^3.4.0MITImage caching
video_player^2.11.0BSD-3Inline video
url_launcher^6.3.0BSD-3Open action URLs
http^1.6.0BSD-3HTTP requests
mime^2.0.0BSD-3MIME detection
intl^0.20.2BSD-3Date formatting

Known Limitations

LimitationImpactWorkaround
iOS & Android onlyWeb/Desktop not supportedUse the Web Chatbot SDK for web
flutter_inappwebview and permission_handler must be direct dependenciesHost app must add themAdd both to the host pubspec.yaml
Calendar message type not yet implementedEnxMessageType.calendar renders as textPlanned for v1.1.0
No offline queueMessages fail silently when disconnectedMonitor statusStream and prompt retry
Browser calls onlyNo native call pathStart native calls from your own calling SDK
Android WebView versionRequires Android System WebView 67+Advise users to update

Troubleshooting

Status never reaches connected

  • Check that botId and host are correct.
  • Confirm network connectivity to host.
  • Set onError before initialize() and look for bridge_error or socket_error.

Images/videos don't autoplay on Android

  • The plugin configures the WebView for this automatically (enxConfigureAndroidWebViewMediaPermissions).
  • Check that minSdkVersion is at least 21 and Android System WebView is up to date.

MissingPluginException for flutter_inappwebview

  • Add flutter_inappwebview: ^6.1.5 and permission_handler to the host app's pubspec.yaml.
  • Run flutter pub get and do a full rebuild.

File upload fails on iOS

  • Add all the NS*UsageDescription keys to Info.plist.
  • Request permissions before calling sendFile.
  • Check onError for file_upload_error.

Black screen in the call view

  • Confirm the iFrameUrl is HTTPS.
  • Add an NSAppTransportSecurity exception if needed for development.

License

This plugin is proprietary software owned by EnableX / VCloudX Infotech. All rights reserved. Redistribution requires written permission.

Support