Skip to content

Instantly share code, notes, and snippets.

@vibalijoshi
Created October 12, 2021 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vibalijoshi/87c5e6c310b0e6e0a54c2409bee751cb to your computer and use it in GitHub Desktop.
Save vibalijoshi/87c5e6c310b0e6e0a54c2409bee751cb to your computer and use it in GitHub Desktop.
Final WebSocket Flutter Demo
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:web_socket_channel/io.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
WebSocketChannel channel = IOWebSocketChannel.connect("wss://ws.ifelse.io/");
@override
MyHomePageState createState() {
return MyHomePageState();
}
}
class MyHomePageState extends State<MyHomePage> {
TextEditingController _controller = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Web Socket"),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Form(
child: TextFormField(
decoration: InputDecoration(labelText: "Send any message to the server"),
controller: _controller,
),
),
StreamBuilder(
stream: widget.channel.stream,
builder: (context, snapshot) {
return Padding(
padding: const EdgeInsets.all(20.0),
child: Text(snapshot.hasData ? '${snapshot.data}' : ''),
);
},
)
],
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.send),
onPressed: sendData,
),
);
}
void sendData() {
if (_controller.text.isNotEmpty) {
widget.channel.sink.add(_controller.text);
}
}
@override
void dispose() {
widget.channel.sink.close();
super.dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment