团队作业博客(八)flutter调用环信sdk 实现即时通讯
首先创建应用
之后 在flutter中 添加依赖
im_flutter_sdk: ^4.5.0
打开quick_start/lib/main.dart
文件,引入头文件
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
添加下面代码
import 'package:flutter/material.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
class LoginPage2 extends StatefulWidget {
const LoginPage2();
@override
_LoginPage2 createState() => _LoginPage2();
}
class _LoginPage2 extends State<LoginPage2> {
ScrollController scrollController = ScrollController();
String _username = "";
String _password = "";
String _messageContent = "";
String _chatId = "";
final List<String> _logText = [];
@override
void initState() {
super.initState();
_initSDK();
_addChatListener();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('登录'),
),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
decoration: const InputDecoration(hintText: "输入用户名"),
onChanged: (username) => _username = username,
),
TextField(
decoration: const InputDecoration(hintText: "输入密码"),
onChanged: (password) => _password = password,
),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Expanded(
flex: 1,
child: TextButton(
onPressed: _signIn,
child: const Text("登录"),
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all(Colors.white),
backgroundColor: MaterialStateProperty.all(Colors.lightBlue),
),
),
),
const SizedBox(width: 10),
Expanded(
child: TextButton(
onPressed: _signOut,
child: const Text("退出"),
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all(Colors.white),
backgroundColor: MaterialStateProperty.all(Colors.lightBlue),
),
),
),
const SizedBox(width: 10),
Expanded(
child: TextButton(
onPressed: _signUp,
child: const Text("注册"),
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all(Colors.white),
backgroundColor: MaterialStateProperty.all(Colors.lightBlue),
),
),
),
],
),
const SizedBox(height: 10),
TextField(
decoration: const InputDecoration(
hintText: "输入接收者用户名",
),
onChanged: (chatId) => _chatId = chatId,
),
TextField(
decoration: const InputDecoration(hintText: "输入消息"),
onChanged: (msg) => _messageContent = msg,
),
const SizedBox(height: 10),
TextButton(
onPressed: _sendMessage,
child: const Text("发送消息"),
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all(Colors.white),
backgroundColor: MaterialStateProperty.all(Colors.lightBlue),
),
),
Flexible(
child: ListView.builder(
controller: scrollController,
itemBuilder: (_, index) {
return Text(_logText[index]);
},
itemCount: _logText.length,
),
),
],
),
),
);
}
void _initSDK() async {
EMOptions options = EMOptions(
appKey: "1169240414209351#youxiandechulun",
autoLogin: false,
);
await EMClient.getInstance.init(options);
// 通知sdk ui已经准备好,执行后才会收到`EMChatRoomEventHandler`, `EMContactEventHandler`, `EMGroupEventHandler` 回调。
await EMClient.getInstance.startCallback();
}
void _addChatListener() {
// 添加消息状态变更监听
EMClient.getInstance.chatManager.addMessageEvent(
// ChatMessageEvent 对应的 key。
"UNIQUE_HANDLER_ID",
ChatMessageEvent(
onSuccess: (msgId, msg) {
_addLogToConsole("发送消息成功");
},
onProgress: (msgId, progress) {
_addLogToConsole("发送消息成功");
},
onError: (msgId, msg, error) {
_addLogToConsole(
"发送消息失败,代码: ${error.code}, 描述: ${error.description}",
);
},
));
// 添加收消息监听
EMClient.getInstance.chatManager.addEventHandler(
// EMChatEventHandle 对应的 key。
"UNIQUE_HANDLER_ID",
EMChatEventHandler(
onMessagesReceived: (messages) {
for (var msg in messages) {
switch (msg.body.type) {
case MessageType.TXT:
{
EMTextMessageBody body = msg.body as EMTextMessageBody;
_addLogToConsole(
"接收到文本消息: ${body.content}, 来自: ${msg.from}",
);
}
break;
case MessageType.IMAGE:
{
_addLogToConsole(
"接收到图片消息, 来自: ${msg.from}",
);
}
break;
case MessageType.VIDEO:
{
_addLogToConsole(
"接收到视频消息, 来自: ${msg.from}",
);
}
break;
case MessageType.LOCATION:
{
_addLogToConsole(
"接收到位置消息, 来自: ${msg.from}",
);
}
break;
case MessageType.VOICE:
{
_addLogToConsole(
"接收到语音消息, 来自: ${msg.from}",
);
}
break;
case MessageType.FILE:
{
_addLogToConsole(
"接收到文件消息, 来自: ${msg.from}",
);
}
break;
case MessageType.CUSTOM:
{
_addLogToConsole(
"接收到自定义消息, 来自: ${msg.from}",
);
}
break;
case MessageType.CMD:
{
// 当前回调中不会有 CMD 类型消息,CMD 类型消息通过 [EMChatEventHandler.onCmdMessagesReceived] 回调接收
}
break;
case MessageType.COMBINE:
// TODO: Handle this case.
}
}
},
),
);
}
void _signIn() async {
if (_username.isEmpty || _password.isEmpty) {
_addLogToConsole("用户名或密码为空");
return;
}
try {
await EMClient.getInstance.login(_username, _password);
_addLogToConsole("登录成功, 用户名: $_username");
} on EMError catch (e) {
_addLogToConsole("登录失败, 错误代码: ${e.code} , ${e.description}");
}
}
void _signOut() async {
try {
await EMClient.getInstance.logout(true);
_addLogToConsole("退出成功");
} on EMError catch (e) {
_addLogToConsole(
"退出失败, 代码: ${e.code}, 描述: ${e.description}");
}
}
void _signUp() async {
if (_username.isEmpty || _password.isEmpty) {
_addLogToConsole("用户名或密码为空");
return;
}
try {
_addLogToConsole("开始创建账号...");
await EMClient.getInstance.createAccount(_username, _password);
_addLogToConsole("创建账号成功, 用户名: $_username");
} on EMError catch (e) {
_addLogToConsole(
"创建账号失败, 代码: ${e.code}, 描述: ${e.description}");
}
}
void _sendMessage() async {
if (_chatId.isEmpty || _messageContent.isEmpty) {
_addLogToConsole("聊天ID或消息内容为空");
return;
}
var msg = EMMessage.createTxtSendMessage(
targetId: _chatId,
content: _messageContent,
);
EMClient.getInstance.chatManager.sendMessage(msg);
}
void _addLogToConsole(String log) {
_logText.add(_timeString + ": " + log);
setState(() {
scrollController.jumpTo(scrollController.position.maxScrollExtent);
});
}
String get _timeString {
return DateTime.now().toString().split(".").first;
}
}
实现