Using the ably flutter package, how can I subscribe to and listen to an event in Laravel and Flutter?

417 Views Asked by At

I'm developing a chat application using Laravel and flutter. I'm using ably_flutter package to make it realtime. The channel is created successfully but it's faild to listen an event or a message.

final clientOptions = ably.ClientOptions( 
      key: 'rVPjew.ydfBPA:JqRRY9JI49_L9l8CsfvMxXuxhMeyQzgEo6apWE');

 subscribeAbly() async {
    ably.Realtime realtime = ably.Realtime(options: clientOptions);

    realtime.connection
        .on(ably.ConnectionEvent.connected)
        .listen((ably.ConnectionStateChange stateChange) async {
print(stateChange.current)// connected
      ably.RealtimeChannel channel = realtime.channels.get('public.room');
      channel.subscribe(name: 'message.new').listen((ably.Message message) {
        print("message is fired");//it's not working
        final data = jsonEncode(message.data);
        final response = jsonDecode(data)['message'] as Map<String, dynamic>;
        setState(() {
          mapData.insert(0, {"message": "From ably", "is_sender": false});
        });
      });
    });

   @override
   initState(){
   super.initState();
    subscribeAbly()
 }      

I'm using Flutter 2.8 and ably_flutter 1.2.15 Any assistance would be much appreciated.

1

There are 1 best solutions below

2
On

As a debugging step, if you publish a message from within flutter to this channel using channel.publish() do you receive an event?

If not then something might be wrong with your setup in Flutter. One thing I'd try would be to move the realtime object declaration outside of the async function scope and make it a property instead.

Other than that - again as a debugging step try to subscribe to all events on the channel:

channel.subscribe()

instead of:

channel.subscribe(name: 'message.new')

and double check if the channel name is correct and you've set up Laravel to publish messages to the same channel:

realtime.channels.get('public.room')

Could you also please elaborate on how you are publishing messages on the laravel side?