flutter|flutter websocket 客户端

1、pubspec文件管理Flutter应用程序的assets(资源,如图片、package等)。 在pubspec.yaml中,通过网址“https://pub.dartlang.org/packages/web_socket_channel”确认版本号后,将web_socket_channel (1.0.9或更高版本)添加到依赖项列表。
2、在Android Studio的编辑器视图中查看pubspec时,单击右上角的 Packages get,或者在命令行输入“flutter packages get”;这会将依赖包安装到您的项目。
【flutter|flutter websocket 客户端】3、运行以下代码

import 'package:flutter/foundation.dart'; import 'package:web_socket_channel/io.dart'; import 'package:flutter/material.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget{ @override Widget build(BuildContext context){ final title = 'WebSocket Demo'; return new MaterialApp( title:title, home: new MyHomePage( title: title, channel: new IOWebSocketChannel.connect('ws://echo.websocket.org'),//如果是本地直接使用IP地址而非localhost或127.0.0.1 ), ); } }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()=> new _MyHomePageState(); }class _MyHomePageState extends State{ TextEditingController _controller = new TextEditingController(); @override Widget build(BuildContext context){ return new Scaffold( appBar: new AppBar( title: new Text(widget.title), ), body: new Padding( padding: const EdgeInsets.all(20.0), child: new Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ new Form( child: new TextFormField( controller: _controller, decoration: new InputDecoration(labelText: 'Send a message'), ), ), new StreamBuilder( stream: widget.channel.stream, builder: (context, snapshot){ return new Padding( padding: const EdgeInsets.symmetric(vertical: 24.0), child: new Text(snapshot.hasData?'${snapshot.data}':''), ); }), ], ), ), floatingActionButton: new FloatingActionButton( onPressed: _sendMessage, tooltip: 'Send message', child: new Icon(Icons.send), ), ); } void _sendMessage(){ if (_controller.text.isNotEmpty){ widget.channel.sink.add(_controller.text); print("send message completed"); } } @override void dispose(){ widget.channel.sink.close(); super.dispose(); } }

    推荐阅读