<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Musab</title>
    <description>The latest articles on DEV Community by Musab (@mu53b).</description>
    <link>https://dev.to/mu53b</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F650760%2F8b60664f-d103-470e-8159-2530c9c27b37.jpg</url>
      <title>DEV Community: Musab</title>
      <link>https://dev.to/mu53b</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mu53b"/>
    <language>en</language>
    <item>
      <title>How to use Flutter Riverpod with Socket.io</title>
      <dc:creator>Musab</dc:creator>
      <pubDate>Fri, 14 Oct 2022 02:54:14 +0000</pubDate>
      <link>https://dev.to/mu53b/how-to-use-flutter-riverpod-with-socketio-47ch</link>
      <guid>https://dev.to/mu53b/how-to-use-flutter-riverpod-with-socketio-47ch</guid>
      <description>&lt;p&gt;Hi Everyone &lt;br&gt;
in this small article I'll show you to use &lt;strong&gt;socket.io&lt;/strong&gt; with &lt;strong&gt;flutter riverpod&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I'm assuming you already have basic knowledge about &lt;strong&gt;flutter riverpod&lt;/strong&gt; and  &lt;strong&gt;socketio&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;*&lt;em&gt;first we will make node socket io server code  *&lt;/em&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;1- make new folder &lt;em&gt;name it as you like&lt;/em&gt;&lt;br&gt;
2- run &lt;em&gt;npm init -y&lt;/em&gt;&lt;br&gt;
3- make file named server.js&lt;/p&gt;

&lt;p&gt;paste the following code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

//Whenever someone connects this gets executed
io.on('connection', function (socket) {

    console.log('A user connected');

    //Whenever someone disconnects this piece of code executed
    socket.on('disconnect', function () {
        console.log('A user disconnected');
    });

    socket.on('message', function (data) {
        // when server receives event called message
        // it convert the mesage to upper case
        // then split it to array
        var newMessage = [...data.toUpperCase()];
        console.log(newMessage);
        socket.emit('broadcast', newMessage);
    })
});

// i'm exposing to to my wifi ip because i'm debugging using adb
http.listen(3000, '192.168.62.123', function () {
    // to work locally use the followning line 
// http.listen(3000,  function () {

    console.log('listening on *:3000');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;then in terminal run node server.js&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;secondly we'll work on flutter application&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;1- create new flutter project &lt;br&gt;
'flutter create my_project_name'&lt;br&gt;
2- install packages , paste in pubsec.yaml &lt;br&gt;
  socket_io_client: *&lt;br&gt;
  flutter_riverpod: *&lt;/p&gt;

&lt;p&gt;create class SocketService&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class SocketService {
  IO.Socket socket = IO.io(
      // im using adb so i need to use my wifi ip
      'http://192.168.62.123:3000',
      IO.OptionBuilder()
          .setTransports(['websocket']) // for Flutter or Dart VM
          .disableAutoConnect() // disable auto-connection
          // .setExtraHeaders({'foo': 'bar'}) // optional
          .build());

  initConnection() {
    socket.connect();
    socket.on('connection', (_) {
      log('connect ${_.toString()}');
    });
    log('Trying Connection');
    socket.onConnect((_) {
      log('connect');
    });

    socket.onerror((_) {
      log('Error Is ${_.toString()}');
    });
  }

  sendMessage(message) {
    socket.emit('message', message);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;call the initConnection function on main&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void main() {
  // call initial connection in the main
  // assuming you want the connection to be continuous
  SocketService().initConnection();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;create ConsumerWidget&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class StreamProviderWithConsumer extends ConsumerWidget {
  const StreamProviderWithConsumer({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {

    return Scaffold(appBar: AppBar(), body: Center());
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;add stream provider&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;final providerOfSocket = StreamProvider.autoDispose((ref) async* {
  StreamController stream = StreamController();

  SocketService().socket.onerror((err) =&amp;gt; log(err));
  SocketService().socket.onDisconnect((_) =&amp;gt; log('disconnect'));
  SocketService().socket.on('fromServer', (_) =&amp;gt; log(_));

  SocketService().socket.on('broadcast', (data) {
    stream.add(data);

    log(data.toString());
  });

  SocketService().socket.onerror((_) {
    log("Error IS ${_.toString()}");
  });

  /** if you using .autDisopose */
  // ref.onDispose(() {
  //   // close socketio
  //   _stream.close();
  //   SocketService().socket.dispose();
  // });

  await for (final value in stream.stream) {
    log('stream value =&amp;gt; ${value.toString()}');
    yield value;
  }
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;watch stream provider inside the consumer widget&lt;br&gt;
&lt;code&gt;final message = ref.watch(providerOfSocket);&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;add next line&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   Center(
              child: message.when(
                  data: (data) {
                    return Text(data.toString());
                  },
                  error: (_, __) {
                    log(_.toString());
                    return const Text('Error');
                  },
                  loading: () =&amp;gt; const Text('Loading ')),
            )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;now when there 'broadcast' event fired , you'll The text will change &lt;/p&gt;

&lt;p&gt;next  I'll add TextEditingController and TextField &lt;br&gt;
so i can send any string it will be processed and return back to me &lt;/p&gt;

&lt;p&gt;the full &lt;br&gt;
consumer widget code will be&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class StreamProviderWithConsumer extends ConsumerWidget {
  const StreamProviderWithConsumer({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    TextEditingController _controller = TextEditingController();
    final message = ref.watch(providerOfSocket);

    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Column(
          children: [
            SizedBox(
              height: 50,
              width: 250,
              child: TextField(
                controller: _controller,
              ),
            ),
            ElevatedButton(
                onPressed: () =&amp;gt; SocketService().sendMessage(_controller.text),
                child: const Text('Send Message')),
            const Divider(),
            Center(
              child: message.when(
                  data: (data) {
                    return Text(data.toString());
                  },
                  error: (_, __) {
                    log(_.toString());
                    return const Text('Error');
                  },
                  loading: () =&amp;gt; const Text('Loading ')),
            )
          ],
        ),
      ),
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://github.com/muxab/flutter_riverpod_socketio"&gt;see the full code&lt;/a&gt;&lt;/p&gt;

</description>
      <category>riverpod</category>
      <category>socketio</category>
      <category>flutter</category>
    </item>
  </channel>
</rss>
