Mich25educ
Mich25educ

Reputation: 333

How to use Laravel Echo with Socket.io in Ffutter

I am working on a flutter project which uses Laravel echo with socket.io for chats in the backend. it was quite easy to implement in the web version with the Laravel echo package, but I am clueless on what to use for Flutter to connect and listen for events. Please I need Help!

Upvotes: 1

Views: 1502

Answers (1)

Akif
Akif

Reputation: 7660

You can follow this blog.

Here are two simple methods:

sendSingleChatMessage(ChatMessageModel chatMessageModel, User toChatUser) {
    print('Sending Message to: ${toChatUser.name}, ID: ${toChatUser.id}');
    if (null == _socket) {
      print("Socket is Null, Cannot send message");
      return;
    }
    _socket.emit("single_chat_message", [chatMessageModel.toJson()]);
}
setOnChatMessageReceivedListener(Function onChatMessageReceived) {
    _socket.on(ON_MESSAGE_RECEIVED, (data) {
      print("Received $data");
      onChatMessageReceived(data);
    });
}

Edit: There is another package to use in here.

// Create echo instance
Echo echo = new Echo({
  'broadcaster': 'socket.io',
  'client': IO.io,
});

// Listening public channel
echo.channel('public-channel').listen('PublicEvent', (e) {
  print(e);
});

// Listening private channel
// Needs auth. See details how to authorize channel below in guides
echo.private('private-channel').listen('PrivateEvent', (e) {
  print(e);
});

// Listening presence channel
// Needs auth. See details how to authorize channel below in guides
echo.join('presence-channel')
  .here((users) {
    print(users);
  }).joining((user) {
    print(user);
  }).leaving((user) {
    print(user);
  }).listen('PresenceEvent', (e) {
    print(e);
  });

// Accessing socket instance
echo.socket.on('connect', (_) => print('connected'));
echo.socket.on('disconnect', (_) => print('disconnected'));

Upvotes: 1

Related Questions