To connect to the Socket.io server using Flutter, you need to use the socket_io_client
package and provide the following headers: userId, type, and
token.
import 'package:socket_io_client/socket_io_client.dart' as IO;
void main() {
IO.Socket socket = IO.io('http://localhost:4000', {
'transports': ['websocket'],
'extraHeaders': {
'userid': 'yourUserId',
'type': 'yourType',
'token': 'yourToken'
}
});
socket.on('connect', (_) {
print('Connected');
socket.on('connected', (data) => print('Connected: \$data'));
});
socket.on('error', (message) => print('Error: \$message'));
// Handle disconnection
socket.on('disconnect', (_) => print('Disconnected'));
}
Send a new request to another user.
void sendNewRequest(IO.Socket socket) {
socket.emit('newRequest', {
'userId': 'targetUserId',
'userType': 'targetType',
'requestType': 'requestType',
'data': { /* request data */ }
});
socket.on('request', (data) {
print('New request received: \$data');
});
}
Accept a received request.
void acceptRequest(IO.Socket socket) {
socket.emit('accept', {
'userId': 'targetUserId',
'userType': 'targetType',
'requestType': 'requestType',
'data': { /* acceptance data */ }
});
socket.on('accepted', (data) {
print('Request accepted: \$data');
});
}
Start a chat with another user.
void startChatRequest(IO.Socket socket) {
socket.emit('startChatRequest', {
'userId': 'targetUserId',
'userType': 'targetType',
'requestType': 'requestType',
'data': { /* chat data */ }
});
socket.on('openChat', (data) {
print('Chat started: \$data');
});
}
Reject a received request.
void rejectRequest(IO.Socket socket) {
socket.emit('reject', {
'userId': 'targetUserId',
'userType': 'targetType',
'requestType': 'requestType',
'data': { /* rejection data */ }
});
socket.on('rejected', (data) {
print('Request rejected: \$data');
});
}
Notify that the user is busy.
void notifyUserBusy(IO.Socket socket) {
socket.emit('userBusy', {
'userId': 'targetUserId',
'userType': 'targetType',
'message': 'User is busy'
});
socket.on('busy', (data) {
print('User busy notification received: \$data');
});
}
All errors will be emitted with the event name error.
socket.on('error', (message) {
print('Error: \$message');
});