Send your first message
Verify the first one-to-one or group text-message flow in a Flutter app.
This page shows how to install and initialize OpenIMClientSDK in a Flutter app, log in, and send the first text message. Complete the prerequisites in Before you start first.
For a one-to-one message, provide the recipient's userID. For a group message, provide the destination groupID. Do not provide both destinations.
Step 1: Install the SDK
flutter pub add flutter_openim_sdkThis command selects the latest compatible version from pub.dev and updates pubspec.yaml and the dependency lockfile. Commit the lockfile in team projects. After an upgrade, verify initialization, login, sending, and receiving again.
Step 2: Initialize the SDK
Follow Integrate for each runtime to obtain an application data directory and call initSDK(). Provide an OnConnectListener during initialization and use onConnectSuccess to determine when the connection is available.
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
final initialized = await OpenIM.iMManager.initSDK(
platformID: platformID,
apiAddr: session.apiAddr,
wsAddr: session.wsAddr,
dataDir: dataDir,
listener: connectListener,
);Step 3: Log in
await OpenIM.iMManager.login(
userID: session.userID,
token: session.token,
);Completion of the login() Future and arrival of OnConnectListener.onConnectSuccess are separate stages. Send the message only after the connection-success callback arrives.
Step 4: Prepare the destination
A one-to-one message requires an existing recipient:
const targetUserID = 'user_b';A group message requires a group in which the current user is permitted to send messages:
const targetGroupID = 'group_123';Step 5: Create and send a text message
First call createTextMessage() to create a local Message, then pass it to sendMessage(). Creating the message does not send it or trigger a receive event.
final message = await OpenIM.iMManager.messageManager.createTextMessage(
text: 'Hello, OpenIMSDK',
);
final sentMessage = await OpenIM.iMManager.messageManager.sendMessage(
message: message,
userID: targetUserID,
offlinePushInfo: OfflinePushInfo(
title: 'New message',
desc: 'You received a message',
),
);
appendOutgoingMessage(sentMessage);For a group message, provide groupID instead of userID:
final sentMessage = await OpenIM.iMManager.messageManager.sendMessage(
message: message,
groupID: targetGroupID,
offlinePushInfo: OfflinePushInfo(
title: 'New group message',
desc: 'A new message was sent to the group',
),
);After the sendMessage() Future succeeds, merge the returned Message into the current client's local message list by clientMsgID. Another logged-in client receives the new message through the message listener; see Receive messages for the complete listener. Verify the successful Future and the recipient's callback separately.
Next steps
Was this page helpful?