mercredi 6 décembre 2023

How can I use websockets in Flutter?

I am trying to implement WebSockets for a Laravel-Flutter project. For the Laravel side, I followed these steps. If you see anything wrong or missing, please feel free to say:

https://gist.github.com/emir-ekin-ors/79e670eb6ea970af38c476a8087c19ea

When I test it with Tinker, I can see the event in the dashboard. So I assume the Laravel part is working properly.

The problem is when I try to listen to the channel in Flutter. I can't see anything on the terminal. I tried to follow the documentation of the web_socket_channel package. I am open to all the suggestions since I know nothing about websockets. You can find the Flutter code below:


import 'dart:async';

import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

void main() {
    runApp(MyApp());
}

class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
        return MaterialApp(
            home: MyWebSocketScreen(),
        );
    }
}

class MyWebSocketScreen extends StatefulWidget {
    @override
    _MyWebSocketScreenState createState() => _MyWebSocketScreenState();
}

class _MyWebSocketScreenState extends State<MyWebSocketScreen> {
    late final _channel;
    late StreamSubscription _streamSubscription;

    @override
    void initState() {
        super.initState();
        _channel = WebSocketChannel.connect(Uri.parse('wss://localhost:6001'));
        _streamSubscription = _channel.stream.listen((data) {
            print('Received: $data');
        }, onError: (error) {
            print('Error: $error');
        });
    }

    @override
    Widget build(BuildContext context) {
        return Placeholder();
    }

    @override
    void dispose() {
        _streamSubscription.cancel();
        _channel.sink.close();
        super.dispose();
    }
}

This is the NewMessage class in Laravel if it necessary:


<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class NewMessage implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

    public function __construct($message)
    {
        $this->message = $message;
    }

    public function broadcastOn(): array
    {
        return [
            new Channel('home'),
        ];
    }
}


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire