Skip to content

Instantly share code, notes, and snippets.

@mmaitlen
Created July 11, 2024 00:26
Show Gist options
  • Select an option

  • Save mmaitlen/9c51792cff715deb58f167ff8e9791c2 to your computer and use it in GitHub Desktop.

Select an option

Save mmaitlen/9c51792cff715deb58f167ff8e9791c2 to your computer and use it in GitHub Desktop.
A simple Flutter/Dart websocket client
/// A simple websocket client Flutter app
/// thanks to Simon Lightfoot @devangelslondon and Craig Labenz @craig_labenz
/// #boringshow https://youtu.be/AaQzV1LTmo0?si=2xjcfH0FA5tt4nyW
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
void main() {
runApp(const MainApp());
}
class MainApp extends StatefulWidget {
const MainApp({super.key});
@override
State<MainApp> createState() => _MainAppState();
}
class _MainAppState extends State<MainApp> {
late WebSocketChannel channel;
@override
void initState() {
super.initState();
final wsUrl = Uri.parse('ws://localhost:8081/ws');
channel = WebSocketChannel.connect(wsUrl);
channel.stream.listen((event) {
debugPrint('got stuff from server $event');
});
}
@override
void dispose() {
channel.sink.close();
super.dispose();
}
void pingServer() {
debugPrint("ping server");
channel.sink.add('bobdog');
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
children: [
const Text('CLIENT!'),
ElevatedButton(
onPressed: pingServer,
child: const Text("Ping Server"),
)
],
),
),
),
);
}
}
name: websocket_client
description: "Websocket client"
publish_to: 'none'
version: 0.1.0
environment:
sdk: '>=3.2.6 <4.0.0'
dependencies:
flutter:
sdk: flutter
web_socket_channel: ^2.4.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
flutter:
uses-material-design: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment