Search code examples
flutterdartwebsocketlaravel-echo

Make multiple instances of Laravel Echo for Flutter


i'm trying to add websockets in flutter application using this package: laravel_echo: ^0.2.9.

I have Notifications and Messages in my application, so if i create websocket for only of the two it works fine. However if i add the second websocket they all stop working.

Code snipet:

pusher_socket.dart


class PusherSocket {
  
   Echo socket({ String authToken }){

        PusherAuth _auth = PusherAuth(
          'https://api.example.com/broadcasting/auth',
          headers: {
            'Authorization': '$authToken',
          },
        );
        

      PusherOptions options = PusherOptions(
        host: "api.example.com",
        port: 6003,
        encrypted: true,
        auth: _auth,
        cluster: "CLT",
      );

      FlutterPusher pusher = FlutterPusher("MY_KEY", options, enableLogging: false );

      return new Echo({
        'broadcaster': 'pusher',
        'client': pusher,
      });
  }
}

Listening in a page

NB: I want to use this code in different pages

Echo echo = new PusherSocket().socket(authToken: conversationProvider.authToken);

echo
    .join("conversation.${conversationProvider.conversation.id}")
    .listen('NewMessage', (data) {
    print(data);
    try {
        final message = data;

        Message _message = Message.fromJson(message);

        conversationProvider.addMessage(message: _message);
    } catch (error) {
        
    }
});

Is there anything that i'm doing wrong?


Solution

  • Basically you do not neet to creat two instances of websockets for that. You can creat a global websocket then use it across the application.

    Example.

    here i have instantiated websocket inside AuthProvider because i know the AuthProvider will be included in the root of the application, making it available to all sub Widgets:

    pusher_socket.dart

    class PusherSocket {
      
       Echo socket({ String authToken }){
    
            PusherAuth _auth = PusherAuth(
              'https://api.example.com/broadcasting/auth',
              headers: {
                'Authorization': '$authToken',
              },
            );
            
    
          PusherOptions options = PusherOptions(
            host: "api.example.com",
            port: 6003,
            encrypted: true,
            auth: _auth,
            cluster: "CLT",
          );
    
          FlutterPusher pusher = FlutterPusher("MY_KEY", options, enableLogging: false );
    
          return new Echo({
            'broadcaster': 'pusher',
            'client': pusher,
          });
      }
    }
    

    auth_provider.dart

    
    class AuthProvider with ChangeNotifier {
      String authToken;
      Echo echo;
    
      
      Future<void> sigin({@required email, @required password}) async {
    
          /**
           * the logic for login
           * goes here
           */
    
          // Set echo if not set
          if (echo == null && authToken != null) {
            echo = PusherSocket().socket(authToken: authToken);
            print("Prepare echo");
          }
    
          //notify others
          notifyListeners();
      }
    
    

    conversation_page.dart

    
    final authProvider = Provider.of<AuthProvider>(context);
    
    authProvider.echo
        .join("conversation.${conversationProvider.conversation.id}")
        .listen('NewMessage', (data) {
        print(data);
        try {
            final message = data;
    
            Message _message = Message.fromJson(message);
    
            conversationProvider.addMessage(message: _message);
        } catch (error) {
            
        }
    });