首先下載依賴
導包
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}')),
);
}
}
}