Created
April 30, 2020 18:49
-
-
Save paulallies/8ae1ea6fb8d0964c3ad1a9185b9ff7fd to your computer and use it in GitHub Desktop.
Flutter Websockets
This file contains 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
import 'package:flutter/material.dart'; | |
import 'package:web_socket_channel/io.dart'; | |
import 'package:web_socket_channel/web_socket_channel.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
final title = 'WebSocket Demo'; | |
return MaterialApp( | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: MyHomePage( | |
title: title, | |
channel: IOWebSocketChannel.connect( | |
"wss://flexoapi.nanosoft.co.za/wss", | |
)), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
final String title; | |
final WebSocketChannel channel; | |
MyHomePage({ | |
Key key, | |
@required this.title, | |
@required this.channel, | |
}) : super(key: key); | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
TextEditingController _controller = TextEditingController(); | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(widget.title), | |
), | |
body: Padding( | |
padding: const EdgeInsets.all(20.0), | |
child: Column( | |
crossAxisAlignment: CrossAxisAlignment.start, | |
children: <Widget>[ | |
Form( | |
child: TextFormField( | |
controller: _controller, | |
decoration: InputDecoration(labelText: 'Send a message'), | |
), | |
), | |
StreamBuilder( | |
stream: widget.channel.stream, | |
builder: (context, snapshot) { | |
return Padding( | |
padding: const EdgeInsets.symmetric(vertical: 24.0), | |
child: Text(snapshot.hasData ? '${snapshot.data}' : ''), | |
); | |
}, | |
) | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: _sendMessage, | |
tooltip: 'Send message', | |
child: Icon(Icons.send), | |
), // This trailing comma makes auto-formatting nicer for build methods. | |
); | |
} | |
void _sendMessage() { | |
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