text
stringlengths
1
372
in flutter, use the following line to
create a WebSocketChannel that connects to a server:
<code_start>
final channel = WebSocketChannel.connect(
uri.parse('wss://echo.websocket.events'),
);
<code_end>
<topic_end>
<topic_start>
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 a StreamBuilder
widget to listen for new messages, and a
text widget to display them.
<code_start>
StreamBuilder(
stream: channel.stream,
builder: (context, snapshot) {
return Text(snapshot.hasData ? '${snapshot.data}' : '');
},
)
<code_end>
<topic_end>
<topic_start>
how this works
the WebSocketChannel provides a
stream of messages from the server.
the stream class is a fundamental part of the dart:async package.
it provides a way to listen to async events from a data source.
unlike future, which returns a single async response,
the stream class can deliver many events over time.
the StreamBuilder widget connects to a stream
and asks flutter to rebuild every time it
receives an event using the given builder() function.
<topic_end>
<topic_start>
3. send data to the server
to send data to the server,
add() messages to the sink provided
by the WebSocketChannel.
<code_start>
channel.sink.add('Hello!');
<code_end>
<topic_end>
<topic_start>
how this works
the WebSocketChannel provides a
StreamSink to push messages to the server.
the StreamSink class provides a general way to add sync or async
events to a data source.
<topic_end>
<topic_start>
4. close the WebSocket connection
after you’re done using the WebSocket, close the connection:
<code_start>
channel.sink.close();
<code_end>
<topic_end>
<topic_start>
complete example
<code_start>
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
widget build(BuildContext context) {
const title = 'websocket demo';
return const MaterialApp(
title: title,
home: MyHomePage(
title: title,
),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({
super.key,
required this.title,
});
final string title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final TextEditingController _controller = TextEditingController();
final _channel = WebSocketChannel.connect(
uri.parse('wss://echo.websocket.events'),
);
@override
widget build(BuildContext context) {
return scaffold(
appBar: AppBar(
title: text(widget.title),
),