Created
July 11, 2024 00:26
-
-
Save mmaitlen/9c51792cff715deb58f167ff8e9791c2 to your computer and use it in GitHub Desktop.
A simple Flutter/Dart websocket client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// 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"), | |
| ) | |
| ], | |
| ), | |
| ), | |
| ), | |
| ); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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