Browse SDKs · Flutter
Platform
SDKsFlutter

Environment-specific implementation

Initialize OpenIMClientSDK in Android and iOS Flutter apps and manage mobile runtime boundaries.

Copy

Runtime selection

The flutter_openim_sdk package targets Android and iOS Flutter applications. Both platforms share identical Dart managers, data models, and listener contracts, but require platform-specific platform IDs, storage directories, permissions, background execution policies, and native build configurations.

RuntimeplatformIDPrimary considerations
AndroidIMPlatform.androidNetwork permissions, private storage directory, battery optimization rules, and notification push setup.
iOSIMPlatform.iosApp Transport Security (ATS) policies, app sandbox directories, background execution modes, and APNs integration.

For Web, desktop, and Mini-Programs, use their respective dedicated SDKs. Do not assume Flutter support on those runtimes solely because other constants exist in the IMPlatform enum.

Install dependencies

Add the SDK along with path_provider to access the application documents directory:

flutter pub add flutter_openim_sdk path_provider

This command resolves the latest compatible versions and records them in pubspec.yaml. Commit your lockfile to source control. After upgrading dependencies, independently verify the initialization and connection lifecycles on both Android and iOS devices.

Initialize the SDK

Reuse a single instance of OpenIM.iMManager across your application process. Obtain a persistent writable documents directory, select the appropriate platform identifier, and provide the connection listener during initialization.

Code example

import 'dart:io';

import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:path_provider/path_provider.dart';

Future<bool> initializeOpenIM({
  required String apiAddr,
  required String wsAddr,
}) async {
  final directory = await getApplicationDocumentsDirectory();
  final platformID = Platform.isIOS
      ? IMPlatform.ios
      : IMPlatform.android;

  final initialized = await OpenIM.iMManager.initSDK(
    platformID: platformID,
    apiAddr: apiAddr,
    wsAddr: wsAddr,
    dataDir: directory.path,
    logLevel: 6,
    isLogStandardOutput: true,
    listener: OnConnectListener(
      onConnecting: () => updateConnectionState('connecting'),
      onConnectSuccess: () => updateConnectionState('connected'),
      onConnectFailed: (code, message) {
        updateConnectionState('failed');
        logConnectionFailure(code, message);
      },
      onKickedOffline: handleKickedOffline,
      onUserTokenExpired: refreshSession,
      onUserTokenInvalid: redirectToSignIn,
    ),
  );

  return initialized == true;
}

Parameters

ParameterTypeRequiredDescription
platformIDintYesPlatform identifier. Pass IMPlatform.android for Android, and IMPlatform.ios for iOS.
apiAddrStringYesOpenIMServer HTTP API endpoint.
wsAddrStringYesOpenIMServer WebSocket endpoint.
dataDirStringYesApp sandbox directory for local SQLite databases and logs.
listenerOnConnectListenerYesListener for connection state transitions, token expiration, and kick-out events.
logLevelintNoNumeric SDK logging level. Defaults to 6.
isNeedEncryptionboolNoWhether to enable local database encryption. Defaults to false.
isCompressionboolNoWhether to compress network payloads. Defaults to false.
isLogStandardOutputboolNoWhether to print SDK logs to standard output.
logFilePathString?NoCustom log file path. When omitted, the SDK creates logs inside dataDir.

Return value

A successful Future returns a boolean indicating whether the underlying native core was initialized. WebSocket readiness after login is signaled exclusively through the OnConnectListener.onConnectSuccess event.

Android and iOS boundaries

Android

  • Ensure AndroidManifest.xml includes <uses-permission android:name="android.permission.INTERNET"/> and store SDK data in internal app storage.
  • When running on an Android emulator, do not use localhost to refer to the host workstation.
  • Process retention and push message delivery depend on system battery policies and OEM-specific background restrictions.

iOS

  • Store database and cache files strictly within the writable application sandbox; never attempt to write to the app bundle.
  • Configure App Transport Security (ATS) exceptions if connecting to non-HTTPS/WSS staging endpoints. Production deployments require valid TLS certificates.
  • Physical devices, background fetch modes, and simulators exhibit different lifecycle characteristics; verify each independently.

Lifecycle and teardown

The Flutter SDK does not expose manual network status or foreground/background lifecycle reporting methods. When the app resumes, rely on OnConnectListener callbacks to determine connection status, and re-query fresh snapshots for visible screens. When releasing SDK resources completely, invoke:

OpenIM.iMManager.unInitSDK();

Uninitialization is not equivalent to signing out. When switching user accounts, await logout(), clear user-specific UI state, and then log in with the new credentials.

Verification and troubleshooting

  • Verify initialization, login, and onConnectSuccess on at least one physical Android and iOS device.
  • Verify that HTTP, WebSocket, and media storage URLs are reachable from external networks.
  • Test app process termination, backgrounding, and network disconnections to confirm automatic reconnection and screen recovery.
  • Avoid re-initializing the SDK or swapping the global listener across multiple Widgets.

Next steps