How to use Flutter WebSocket

This article is a simple encapsulation of WebSocket, of course, you can also do it yourself.

Take a look at the renderings:

insert image description here

First add dependencies:

web_socket_channel: ^1.1.0
  • 1

Then I distinguish four states for it: connecting, connecting, closing, closing.

Based on the state management method of StreamBuilder, if you don't know StreamBuilder, you can learn it by yourself first.

Next is a management class. The main methods are very commonly used. Let me post this class:



import 'dart:async';

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

enum StatusEnum{
  connect,connecting,close,closing
}
class WebsocketManager{
  static WebsocketManager _singleton;

  WebSocketChannel channel;
  factory WebsocketManager() {
    return _singleton;
  }
   StreamController<StatusEnum> socketStatusController = StreamController<StatusEnum>();
  WebsocketManager._();
  static void init() async {
    if (_singleton == null) {
      _singleton = WebsocketManager._();
    }
  }
  StatusEnum isConnect=StatusEnum.close ; //The default is not connected
  String _url="ws://echo.websocket.org";


  Future connect() async{
    if(isConnect==StatusEnum.close){
      isConnect=StatusEnum.connecting;
      socketStatusController.add(StatusEnum.connecting);
      channel=await IOWebSocketChannel.connect(Uri.parse(_url));
      isConnect=StatusEnum.connect;
      socketStatusController.add(StatusEnum.connect);
       return true;
    }

  }

  Future disconnect() async{
    if(isConnect==StatusEnum.connect){
      isConnect=StatusEnum.closing;
      socketStatusController.add(StatusEnum.closing);
      await channel.sink.close(3000,"active close");
      isConnect=StatusEnum.close;
      socketStatusController.add(StatusEnum.close);

    }

  }

  bool send(String text){
    if(isConnect==StatusEnum.connect) {
      channel.sink.add(text);
      return true;
    }
    return false;
  }

  void printStatus(){
    if(isConnect==StatusEnum.connect){
      print("websocket connected");
    }else if(isConnect==StatusEnum.connecting){
      print("websocket connection");
    }else if(isConnect==StatusEnum.close){
      print("websocket closed");
    }else if(isConnect==StatusEnum.closing){
      print("websocket is closing");
    }
  }

  void dispose(){
    socketStatusController.close();
    socketStatusController=null;
  }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78

Through this management class, you can basically start to open, close, and send these basic functions. I also managed the four states of websocket through StreamBuilder. Let's take a look at my actual case:


import 'package:flutter/material.dart';
import 'package:flutter_websocket/WebsocketManager.dart';

void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  void initState() {
    super.initState();
    //initialization
    WebsocketManager.init();
  }

  @override
  void dispose() {
    WebsocketManager().dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(

        title: Text("How to use Flutter WebSocket?"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton (
              onPressed:() => _send() ,
              child: Text("Send"),
            ),
            RaisedButton (
              onPressed:() => _open() ,
              child: Text("Open websocket connection"),
            ),
            RaisedButton (
              onPressed:() => _close() ,
              child: Text("Close the websocket connection"),
            ),
            RaisedButton (
              onPressed:() => _reconnect() ,
              child: Text("Reconnect websocket connection"),
            ),
            StreamBuilder<StatusEnum>(
              builder: (context, snapshot) {
                if (snapshot.data==StatusEnum.connect){
                  return StreamBuilder(
                    builder: (context, snapshot2) {
                      if(snapshot2.hasData){
                        return Container(
                          child: Text("Received message: ${snapshot2.data}"
                          ),
                        );
                      }else if(snapshot2.hasError){//An error occurred in websocket (not tested here)
                          _reconnect();//Reconnect
                      }

                      return Text("Connected, no data yet");

                    },
                    stream: WebsocketManager().channel.stream,
                  );
                }else if(snapshot.data==StatusEnum.connecting){
                  return Text("Connecting");
                }else if(snapshot.data==StatusEnum.close){
                  return Text("closed");
                }else if(snapshot.data==StatusEnum.closing){
                  return Text("closing");
                }
              },
              initialData: StatusEnum.close,
              stream:WebsocketManager().socketStatusController.stream,
            )
          ],
        ),
      ),
    );
  }
  _open()async {
   await WebsocketManager().connect();
  }
  _close() async{
    await WebsocketManager().disconnect();
  }


 int i=0;
  _send() {
    WebsocketManager().send("Haha ${i+=1}");
  }

  _reconnect() async{
    await _close();
    await _open();
  }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124

Basically the case has been implemented to open, close, reconnect and so on.

Welcome to leave a comment and hurt each other.

Related: How to use Flutter WebSocket