Socket Programming in Flutter, Build Chat Apps in Flutter

By | February 16, 2020

Today’s video will let you know how to create sockets in Flutter to make bi-directional communication possible.

First we will go with the ‘IOWebSocketChannel‘ class.

Watch Video Tutorial

You can read about IOWebSocketChannel by following this link.

Let’s use the Official Sample first.

Create a new file SocketDemo.dart and add the below code into it.

This will create a socket connection with the which will echo back the message we sent to it.

So let’s create a socket

 WebSocketChannel _channel;
_channel = IOWebSocketChannel.connect('ws://');

 void sendMessage() {
    _channel.sink.add('Your Message');

  void dispose() {

// the build method, add this 
  builder: (context, snapshot) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 24.0),
      child: Text(snapshot.hasData ? '${}' : ''),

Now if you call sendMessage, you should get the message back.

If you want to do this with your own server you can use the below code

import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/status.dart' as status;

main() async {
  var channel = await IOWebSocketChannel.connect("ws://<YOUR_SERVER_IP>:<YOUR_PORT>"); {
  }, onDone: () => print("Stream closed"));

Create our own Server Socket

I am using XAMPP for my local server. You can download XAMPP from here.

Create Server File

After running your server, save this file in the htdocs folder.


$host = "";
$port = "6000";

// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Could not create socket');
// bind socket to port
$result  = socket_bind($socket, $host, $port) or die('Could not bind to socket');
// start listening to connections
$result = socket_listen($socket, 3) or die('Could not set up socket listener');

    // accept incoming connections
    // spawn another socket to handle communication
    $spawn = socket_accept($socket) or die('Could not accept incoming connection');
    // read client input
    $input  = socket_read($spawn, 1024) or die('Could not read input');
    // clean up input string
    $input = trim($input);
    echo "Client Message: ".$input;
    // reverse the message and send back
    $output = strrev($input);
    socket_write($spawn, $output, strlen($output)) or die('Could not write output');

// Close sockets


Flutter Sockets

Make sure, you are using the same port as your server and the IP as well.
Also run the server before executing the below code.

Socket _socket;
  static const String SERVER_IP = "";
  static const int SERVER_PORT = 6000;

  Future<bool> sendMessage(String message, Function connectionListener,
      Function messageListener) async {
    try {
      _socket = await Socket.connect(SERVER_IP, SERVER_PORT);
      _socket.listen((List<int> event) {
        String message = utf8.decode(event);
        print('Message: $message');
    } catch (e) {
      return false;
    return true;

  void cleanUp() {
    if (null != _socket) {

Now we have the basic code, you can call this code from your main file like this.

// Call like this
                    connectionListener, messageListener);

// When the socket receives message, this function gets called...check the above code where we're sending this 
// function as the parameter of the sendMessage function.
void messageListener(String message) {
    setState(() {

// When the socket gets connected, this function gets called...check the above code where we're sending this 
// function as the parameter of the sendMessage function.
  void connectionListener(bool connected) {
    setState(() {
      _status = 'Status : ' + (connected ? 'Connected' : 'Failed to connect');

Source Code

You can get the complete source code by cloning this link
git clone

Make sure to switch to “SocketDemo” branch.

3 thoughts on “Socket Programming in Flutter, Build Chat Apps in Flutter

  1. Vaibhav Bahadur

    How to chat between 2 devices? I am able to send messages to the socket connection and get back to the same phone. How about chatting with another phone?

    1. James Post author

      I will be uploading a tutorial on that. Please stay tuned on my youtube channel.

  2. Ro

    Hi James,

    Any update on your tutorial? I want to create a simple group chat page.
    Where people also can see previous chats. I think you also need socket for this right?


Leave a Reply

Your email address will not be published. Required fields are marked *