Skip to content

Instantly share code, notes, and snippets.

@igidio
Created June 12, 2025 15:14
Show Gist options
  • Save igidio/ebe28d5e29e36a93c64657ab3d136617 to your computer and use it in GitHub Desktop.
Save igidio/ebe28d5e29e36a93c64657ab3d136617 to your computer and use it in GitHub Desktop.
Implementing WebSocket in a StatefulWidget
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
class ChatScreen extends StatefulWidget {
@override
_ChatScreenState createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final channel = WebSocketChannel.connect(
Uri.parse('wss://echo.websocket.org'),
);
final TextEditingController controller = TextEditingController();
String lastMessage = "";
void sendMessage() {
if (controller.text.isNotEmpty) {
channel.sink.add(controller.text);
controller.clear();
}
}
@override
void initState() {
super.initState();
channel.stream.listen((message) {
setState(() {
lastMessage = message;
});
});
}
@override
void dispose() {
channel.sink.close();
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("WebSocket Chat")),
body: Padding(
padding: EdgeInsets.all(20),
child: Column(
children: [
Text("Último mensaje: $lastMessage"),
TextField(
controller: controller,
decoration: InputDecoration(labelText: "Escribe un mensaje"),
),
ElevatedButton(onPressed: sendMessage, child: Text("Enviar")),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment