本篇將重點放在處理Flutter client端
一樣也是和GetX做結合
Widget部分 全部貼出來篇幅會很冗長 更細部的請參考置底的GitHub link
class SocketIOPage extends GetView<SocketIOPageController> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Obx(() {
final stateString = controller.isOnConnect ? "已連線" : "未連線";
return Text('聊天室 狀態: $stateString');
}),
actions: [
IconButton(
icon: Icon(Icons.call),
onPressed: () {
controller.makeCall();
},
),
],
),
body: GestureDetector(
onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
child: SafeArea(
child: Obx(
() {
return Column(
children: [
Expanded(child: _buildMessageListView()),
_buildTextFieldRow(),
],
);
},
),
),
),
);
}
controller部分
class SocketIOPageController extends GetxController {
final textEditingController = TextEditingController();
late IO.Socket socket;
final _isOnConnect = false.obs;
set isOnConnect(value) => this._isOnConnect.value = value;
get isOnConnect => this._isOnConnect.value;
final _message = ''.obs;
set message(value) => this._message.value = value;
get message => this._message.value;
//應該是要帶變數 但目前先寫a
final _room = 'a'.obs;
set room(value) => this._room.value = value;
get room => this._room.value;
//應該是要帶變數 但目前先寫Flutter_client
final _userName = 'Flutter_client'.obs;
set userName(value) => this._userName.value = value;
get userName => this._userName.value;
final _messageList = <String>[].obs;
get messageList => _messageList.toList();
@override
onInit() {
connectSokcetIO();
super.onInit();
}
connectSokcetIO() {
//因為我架在自己本機, 大家要把ip要換成自己的
socket = IO.io('ws://192.168.x.xx:8090', <String, dynamic>{
'transports': ['websocket']
});
socket.onConnect((_) {
print('on connect');
// socket.emit('msg', 'test');
isOnConnect = true;
socket.on('joined', (data) {
print('joined');
//room, id
print(data.runtimeType);
print(data);
});
});
socket.on('message', (data) {
print('message: ${data[1]}');
// print(data.runtimeType);
// print(data);
final messageContent = data[1];
_messageList.add(messageContent);
});
socket.onDisconnect((data) {
print('disconnect');
print(data);
});
socket.onConnectError((data) {
print(data);
});
socket.emit('join', room);
}
sendMessage() {
final sendData = userName + ':' + textEditingController.text;
socket.emit('message', [room, sendData]);
textEditingController.text = '';
}
最後一起的大合體
下一篇將為大家介紹 Native_splash