首先下载依赖
导包
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
登录
import 'package:flutter/material.dart';
import 'package:test1/Do/UserDao.dart'; // Make sure this path is correct
import 'package:test1/page/logined.dart';
import 'register.dart'; // Import your RegisterPage class
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
class LoginPage extends StatefulWidget {
LoginPage({required Key key}) : super(key: key);
@override
_LoginPage createState() => _LoginPage();
}
class _LoginPage extends State<LoginPage> {
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.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
TextField(
decoration: const InputDecoration(hintText: "输入用户名"),
onChanged: (username) => _username = username,
),
const SizedBox(height: 20.0),
TextField(
decoration: const InputDecoration(hintText: "输入密码"),
onChanged: (password) => _password = password,
),
const SizedBox(height: 20.0),
ElevatedButton(
onPressed: () {
// Remove extra condition check
if (_username.isNotEmpty && _password.isNotEmpty) {
// 调用后端登录函数
login(context, _username, _password);
// Navigate to MyApp2 with username parameter
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MyApp2(username: _username),
),
);
} else {
// 提示用户输入完整的信息
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('请输入完整的信息'),
),
);
}
_signIn();
},
child: const Text('登录'),
),
const SizedBox(height: 10.0),
TextButton(
onPressed: () {
// Navigate to the RegisterPage
Navigator.push(
context,
MaterialPageRoute(builder: (context) => RegisterPage(key: UniqueKey())),
);
},
child: const Text('注册'),
),
],
),
),
);
}
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;
}
}
注册
import 'package:flutter/material.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import '../Do/UserDao.dart';
class RegisterPage extends StatefulWidget {
const RegisterPage({Key? key}) : super(key: key);
@override
_RegisterPageState createState() => _RegisterPageState();
}
class _RegisterPageState extends State<RegisterPage> {
TextEditingController _usernameController = TextEditingController();
TextEditingController _passwordController = TextEditingController();
TextEditingController _usernameController2 = TextEditingController();
TextEditingController _phoneNumberController = TextEditingController();
TextEditingController _emailController = TextEditingController();
@override
void initState() {
super.initState();
_initSDK();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('注册')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextFormField(
controller: _usernameController,
decoration: const InputDecoration(labelText: '账号'),
),
TextFormField(
controller: _passwordController,
decoration: const InputDecoration(labelText: '密码'),
obscureText: true,
),
TextFormField(
controller: _usernameController2,
decoration: const InputDecoration(labelText: '用户名'),
obscureText: true,
),
TextFormField(
controller: _phoneNumberController,
decoration: const InputDecoration(labelText: '手机号'),
keyboardType: TextInputType.phone,
),
TextFormField(
controller: _emailController,
decoration: const InputDecoration(labelText: '邮箱'),
keyboardType: TextInputType.emailAddress,
),
SizedBox(height: 16),
ElevatedButton(
onPressed:(){
String username = _usernameController.text.trim();
String password = _passwordController.text.trim();
String username2 = _usernameController2.text.trim();
String phoneNumber = _phoneNumberController.text.trim();
String email = _emailController.text.trim();
// 做简单的输入验证,你也可以根据需要增加更多的验证逻辑
if (username.isNotEmpty &&
password.isNotEmpty &&
username2.isNotEmpty &&
phoneNumber.isNotEmpty &&
email.isNotEmpty) {
// 调用后端注册函数
register(context, username, password, username2, phoneNumber, email);
} else {
// 提示用户输入完整的信息
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('请输入完整的信息'),
),
);
}
_signUp();
},
child: const Text('注册'),
),
],
),
),
);
}
void _initSDK() async {
EMOptions options = EMOptions(
appKey: "1169240414209351#youxiandechulun",
autoLogin: false,
);
await EMClient.getInstance.init(options);
await EMClient.getInstance.startCallback();
}
Future<void> _signUp() async {
final username = _usernameController.text.trim();
final password = _passwordController.text.trim();
try {
await EMClient.getInstance.createAccount(username, password);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('注册成功')),
);
// 注册成功后可以做一些清理或导航操作
} on EMError catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('注册失败, 代码: ${e.code}, 描述: ${e.description}')),
);
}
}
}