Authenticate and manage session
Initialize OpenIMClientSDK, log in, query login status, handle connection lifecycle events, and log out.
The OpenIM Flutter SDK configures the local mobile environment through its initialization method, then establishes a persistent WebSocket connection session for the current user via the login API. Before starting authentication, verify that your server endpoints, user account, token, and mobile runtime are properly prepared as described in Before you start.
The complete authentication lifecycle consists of the following steps:
- Call
initSDKand supply anOnConnectListener. - Retrieve the
userID,token,apiAddr, andwsAddrfrom your business backend. - Call
login(), await Future completion, and wait for theonConnectSuccesscallback. - Once the persistent connection is established, query users, friends, conversations, groups, and messages.
- When the user logs out or switches accounts, invoke
logout()and reset local application state.
Retrieve user credentials
Obtain the current user's userID, token, and matching apiAddr and wsAddr from your backend service. See Before you start for data requirements.
The userID is the unique user identifier within OpenIM and must match the subject signed into the token. The mobile client consumes credentials issued by the backend and does not issue tokens directly.
Initialize and configure connection lifecycle
Register the connection listener during SDK initialization so that you do not miss state transitions that occur during login.
Code example
final initialized = await OpenIM.iMManager.initSDK(
platformID: platformID,
apiAddr: apiAddr,
wsAddr: wsAddr,
dataDir: dataDir,
listener: OnConnectListener(
onConnecting: () {
setConnectionState('connecting');
},
onConnectSuccess: () {
setConnectionState('connected');
},
onConnectFailed: (code, errorMsg) {
setConnectionState('failed');
logConnectionFailure(code, errorMsg);
},
onKickedOffline: () {
clearCurrentSession();
showSignedInElsewhereDialog();
},
onUserTokenExpired: () async {
await refreshSessionAndRelogin();
},
onUserTokenInvalid: () {
redirectToSignIn();
},
),
);
if (initialized != true) {
throw StateError('OpenIMClientSDK initialization failed.');
}Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
platformID | int | Yes | Target client platform identifier. Must match the physical platform and server multi-platform login policies. |
apiAddr | String | Yes | OpenIMServer HTTP API endpoint reachable from the mobile device. |
wsAddr | String | Yes | OpenIMServer WebSocket endpoint reachable from the mobile device. |
dataDir | String | Yes | Local storage directory for SDK SQLite databases and logs. Must reside in a private, writable application directory. |
listener | OnConnectListener | Yes | Callback listener for connection, token expiration, and kick-out lifecycle events. |
Return value
A successful Future returning true indicates that the local SDK core was initialized. It does not indicate that the user has logged in or that the WebSocket connection is ready. Initialize the SDK once per application process; do not initialize separate instances inside individual Widgets.
The OnConnectListener reference is held by initSDK(). The SDK does not provide a separate listener removal method. Maintain a centralized listener service across your application to prevent re-registration during Widget rebuilds.
Log in the current user
Invoke login with the user credentials:
Code example
final UserInfo currentUser = await OpenIM.iMManager.login(
userID: session.userID,
token: session.token,
);
setCurrentUser(currentUser);Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
userID | String | Yes | OpenIM user ID. Must match the token subject. |
token | String | Yes | Authentication token issued by your business backend. |
checkLoginStatus | bool | No | Whether to check existing login status first. Defaults to true. |
defaultValue | Future<UserInfo> Function()? | No | Fallback callback invoked if fetching user profile fails. Usually left null to propagate real errors. |
Return value
A successful Future returns a UserInfo object representing the logged-in user, indicating that authentication and local database initialization are complete. The onConnectSuccess callback indicates that the persistent WebSocket connection has been established. Treat Future completion and onConnectSuccess as distinct milestones; wait for connection readiness before initiating real-time messaging workflows.
Do not invoke login concurrently. Disable login buttons while the Future is pending or check the current login state before re-invoking.
Query login status
Check whether the SDK is currently authenticated:
Code example
final status = await OpenIM.iMManager.getLoginStatus();
if (status == LoginStatus.logged) {
final currentUserID = await OpenIM.iMManager.getLoginUserID();
restoreSessionFor(currentUserID);
}| Status | Description |
|---|---|
LoginStatus.logout | SDK is currently logged out. |
LoginStatus.logging | Login is currently in progress. Do not trigger parallel login requests. |
LoginStatus.logged | SDK is authenticated. Verify active network connectivity with OnConnectListener. |
login() returns the UserInfo cached during that session. To fetch updated profile information from the server, see Get self profile.
Querying the login status or current user ID returns the immediate cached state without triggering connection callbacks. Use getLoginUserID() to verify that the active SDK account matches your application state, but do not treat it as a substitute for business backend token validation.
When switching accounts, do not overwrite the session in place. Await logout() on the existing account, clear local state, and then log in with the new credentials.
Handle token expiration and kick-outs
When a token expires or becomes invalid, obtain a new token from your backend and re-authenticate. The onKickedOffline event indicates that the current user was forced offline by another client login or administrative action, which is distinct from an explicit client logout.
The Flutter SDK accepts an OpenIM token directly; it does not distinguish between client-side access and session tokens. Token lifetime, renewal, and revocation policies are governed by your business backend and OpenIMServer configurations.
These lifecycle callbacks do not contain entity merge keys. Isolate state per SDK session and user account. When switching accounts, clear state from pending asynchronous tasks to avoid writing stale data to new views.
Log out
End the active session by invoking logout:
Code example
await OpenIM.iMManager.logout();
clearCurrentSession();Return value
A successful Future indicates that the SDK session has terminated. When switching accounts, wait for logout() to complete, purge the previous account's cache, and then invoke login().
Future completion, connection callbacks, and view teardown represent distinct phases. Await logout() before purging conversation lists, message views, unread counters, and cached state. Do not rely solely on connection state callbacks to conclude that logout succeeded.
To release SDK resources entirely when closing the app, call unInitSDK(). This method frees native runtime memory; it is not a substitute for logout() and should not be invoked during normal page navigation.
Next steps
Was this page helpful?