当前位置:   article > 正文

Flutter--WebSocket_flutter websocket

flutter websocket

借助web_socket_channel: ^2.2.0 

  1. import 'package:flutter/material.dart';
  2. import 'package:web_socket_channel/io.dart';
  3. class SocketPage extends StatefulWidget {
  4. const SocketPage({Key? key}) : super(key: key);
  5. @override
  6. State<StatefulWidget> createState() => _SocketState();
  7. }
  8. class _SocketState extends State<SocketPage> {
  9. final TextEditingController _controller = TextEditingController();
  10. late IOWebSocketChannel channel;
  11. @override
  12. void initState() {
  13. channel = IOWebSocketChannel.connect('wss://echo.websocket.events');
  14. }
  15. @override
  16. Widget build(BuildContext context) {
  17. return Scaffold(
  18. appBar: AppBar(
  19. title: Text("WebSocket(内容回显)"),
  20. ),
  21. body: Padding(
  22. padding: const EdgeInsets.all(20.0),
  23. child: Column(
  24. crossAxisAlignment: CrossAxisAlignment.start,
  25. children: <Widget>[
  26. Form(
  27. child: TextFormField(
  28. controller: _controller,
  29. decoration: InputDecoration(labelText: 'Send a message'),
  30. ),
  31. ),
  32. StreamBuilder(
  33. stream: channel.stream,
  34. builder: (context, snapshot) {
  35. return Text(snapshot.hasData ? '${snapshot.data}' : '');
  36. },
  37. )
  38. ],
  39. ),
  40. ),
  41. floatingActionButton: FloatingActionButton(
  42. onPressed: _sendMessage,
  43. tooltip: 'Send message',
  44. child: Icon(Icons.send),
  45. ),
  46. );
  47. }
  48. void _sendMessage() {
  49. if (_controller.text.isNotEmpty) {
  50. channel.sink.add(_controller.text);
  51. }
  52. }
  53. @override
  54. void dispose() {
  55. channel.sink.close();
  56. super.dispose();
  57. }
  58. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/268660
推荐阅读
相关标签
  

闽ICP备14008679号