Flutter 3.41 is live! Check out theFlutter 3.41 blog post!
Communicate with WebSockets
How to connect to a web socket.
In addition to normal HTTP requests, you can connect to servers usingWebSockets.WebSockets allow for two-way communication with a server without polling.
In this example, connect to atest WebSocket server sponsored by Lob.com. The server sends back the same message you send to it. This recipe uses the following steps:
- 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
# Theweb_socket_channel package provides the tools you need to connect to a WebSocket server.
The package provides aWebSocketChannel that allows you to both listen for messages from the server and push messages to the server.
In Flutter, use the following line to create aWebSocketChannel that connects to a server:
finalchannel=WebSocketChannel.connect(Uri.parse('wss://echo.websocket.events'),);2. Listen for messages from the server
#Now that you've established a connection, listen to messages from the server.
After sending a message to the test server, it sends the same message back.
In this example, use aStreamBuilder widget to listen for new messages, and aText widget to display them.
StreamBuilder(stream:channel.stream,builder:(context,snapshot){returnText(snapshot.hasData?'${snapshot.data}':'');},),How this works
# TheWebSocketChannel provides aStream of messages from the server.
TheStream class is a fundamental part of thedart:async package. It provides a way to listen to async events from a data source. UnlikeFuture, which returns a single async response, theStream class can deliver many events over time.
TheStreamBuilder widget connects to aStream and asks Flutter to rebuild every time it receives an event using the givenbuilder() function.
3. Send data to the server
# To send data to the server,add() messages to thesink provided by theWebSocketChannel.
channel.sink.add('Hello!');How this works
# TheWebSocketChannel provides aStreamSink to push messages to the server.
TheStreamSink class provides a general way to add sync or async events to a data source.
4. Close the WebSocket connection
#After you're done using the WebSocket, close the connection:
channel.sink.close();Complete example
#import'package:flutter/material.dart';import'package:web_socket_channel/web_socket_channel.dart';voidmain()=>runApp(constMyApp());classMyAppextendsStatelessWidget{constMyApp({super.key});@overrideWidgetbuild(BuildContextcontext){consttitle='WebSocket Demo';returnconstMaterialApp(title:title,home:MyHomePage(title:title),);}}classMyHomePageextendsStatefulWidget{constMyHomePage({super.key,requiredthis.title});finalStringtitle;@overrideState<MyHomePage>createState()=>_MyHomePageState();}class_MyHomePageStateextendsState<MyHomePage>{finalTextEditingController_controller=TextEditingController();final_channel=WebSocketChannel.connect(Uri.parse('wss://echo.websocket.events'),);@overrideWidgetbuild(BuildContextcontext){returnScaffold(appBar:AppBar(title:Text(widget.title)),body:Padding(padding:constEdgeInsets.all(20),child:Column(crossAxisAlignment:CrossAxisAlignment.start,children:[Form(child:TextFormField(controller:_controller,decoration:constInputDecoration(labelText:'Send a message'),),),constSizedBox(height:24),StreamBuilder(stream:_channel.stream,builder:(context,snapshot){returnText(snapshot.hasData?'${snapshot.data}':'');},),],),),floatingActionButton:FloatingActionButton(onPressed:_sendMessage,tooltip:'Send message',child:constIcon(Icons.send),),// This trailing comma makes auto-formatting nicer for build methods.);}void_sendMessage(){if(_controller.text.isNotEmpty){_channel.sink.add(_controller.text);}}@overridevoiddispose(){_channel.sink.close();_controller.dispose();super.dispose();}}
Unless stated otherwise, the documentation on this site reflects Flutter 3.38.6. Page last updated on 2025-05-19.View source orreport an issue.