In addition to normal HTTP requests, you can connect to servers usingWebSockets. WebSockets allow for two-way communication with a serverwithout polling.

In this example, you’ll connect to a test server provided bywebsocket.org. The server simply sendsback the same message you send to it.

Directions

  • Connect to a WebSocket server
  • Listen for messages from the server
  • Send Data to the Server
  • Close the WebSocket connection

1. Connect to a WebSocket server

The web_socket_channelpackage provides the tools you’ll need to connect to a WebSocket server.

The package provides a WebSocketChannel that allows you to both listen formessages from the server and push messages to the server.

In Flutter, create a WebSocketChannel that connects to a serverin one line:

  1. final channel = IOWebSocketChannel.connect('ws://echo.websocket.org');

2. Listen for messages from the server

Now that you’ve established a connection, you can listen to messages from theserver.

After you send a message to the test server, it sends the same message back.

How to listen for messages and display them? In this example, you’ll usea StreamBuilderWidget to listen for new messages and aTextWidget to display them.

  1. StreamBuilder(
  2. stream: widget.channel.stream,
  3. builder: (context, snapshot) {
  4. return Text(snapshot.hasData ? '${snapshot.data}' : '');
  5. },
  6. );

How does this work?

The WebSocketChannel provides aStreamof messages from the server.

The Stream class is a fundamental part of the dart:async package. Itprovides a way to listen to async events from a data source. Unlike Future,which returns a single async response, the Stream class can deliver manyevents over time.

The StreamBuilderWidget connects to a Stream and asks Flutter to rebuild every time itreceives an event using the given builder function.

3. Send Data to the Server

In order to send data to the server, add messages to the sink providedby the WebSocketChannel.

  1. channel.sink.add('Hello!');

How does this work

The WebSocketChannel provides aStreamSinkto push messages to the server.

The StreamSink class provides a general way to add sync or async events to adata source.

4. Close the WebSocket connection

After you’re done using the WebSocket, close the connection.To do so, close the sink.

  1. channel.sink.close();

Complete example

  1. import 'package:flutter/foundation.dart';
  2. import 'package:web_socket_channel/io.dart';
  3. import 'package:flutter/material.dart';
  4. import 'package:web_socket_channel/web_socket_channel.dart';
  5. void main() => runApp(MyApp());
  6. class MyApp extends StatelessWidget {
  7. @override
  8. Widget build(BuildContext context) {
  9. final title = 'WebSocket Demo';
  10. return MaterialApp(
  11. title: title,
  12. home: MyHomePage(
  13. title: title,
  14. channel: IOWebSocketChannel.connect('ws://echo.websocket.org'),
  15. ),
  16. );
  17. }
  18. }
  19. class MyHomePage extends StatefulWidget {
  20. final String title;
  21. final WebSocketChannel channel;
  22. MyHomePage({Key key, @required this.title, @required this.channel})
  23. : super(key: key);
  24. @override
  25. _MyHomePageState createState() => _MyHomePageState();
  26. }
  27. class _MyHomePageState extends State<MyHomePage> {
  28. TextEditingController _controller = TextEditingController();
  29. @override
  30. Widget build(BuildContext context) {
  31. return Scaffold(
  32. appBar: AppBar(
  33. title: Text(widget.title),
  34. ),
  35. body: Padding(
  36. padding: const EdgeInsets.all(20.0),
  37. child: Column(
  38. crossAxisAlignment: CrossAxisAlignment.start,
  39. children: <Widget>[
  40. Form(
  41. child: TextFormField(
  42. controller: _controller,
  43. decoration: InputDecoration(labelText: 'Send a message'),
  44. ),
  45. ),
  46. StreamBuilder(
  47. stream: widget.channel.stream,
  48. builder: (context, snapshot) {
  49. return Padding(
  50. padding: const EdgeInsets.symmetric(vertical: 24.0),
  51. child: Text(snapshot.hasData ? '${snapshot.data}' : ''),
  52. );
  53. },
  54. )
  55. ],
  56. ),
  57. ),
  58. floatingActionButton: FloatingActionButton(
  59. onPressed: _sendMessage,
  60. tooltip: 'Send message',
  61. child: Icon(Icons.send),
  62. ), // This trailing comma makes auto-formatting nicer for build methods.
  63. );
  64. }
  65. void _sendMessage() {
  66. if (_controller.text.isNotEmpty) {
  67. widget.channel.sink.add(_controller.text);
  68. }
  69. }
  70. @override
  71. void dispose() {
  72. widget.channel.sink.close();
  73. super.dispose();
  74. }
  75. }

Web Sockets Demo