最近在折腾flutter web的相关内容,发现网上相关资源比较少。
(本来还想试试用tcp socket,才知道web并不支持这玩意。。。最后只能选webSocket)
找了好久,遇到了各种问题,确实,flutte web 现在还不是很成熟,但是还是让我发现了支持webSocket的pub包(绕来绕去,还是绕到原来的地方)
在web_socket_channel
简介的最底部发现了。

pub包
在pubspec.yaml中添加
dependencies:
flutter:
sdk: flutter
web_socket_channel: ^1.1.0
DEMO
参考 《Flutter 实战》
import 'package:flutter/material.dart';
import 'package:web_socket_channel/html.dart';
class WebSocketRoute extends StatefulWidget {
@override
_WebSocketRouteState createState() => new _WebSocketRouteState();
}
class _WebSocketRouteState extends State<WebSocketRoute> {
TextEditingController _controller = new TextEditingController();
HtmlWebSocketChannel channel;
String _text = "";
@override
void initState() {
channel = new HtmlWebSocketChannel.connect('ws://echo.websocket.org');
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("WebSocket(内容回显)"),
),
body: new Padding(
padding: const EdgeInsets.all(20.0),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Form(
child: new TextFormField(
controller: _controller,
decoration: new InputDecoration(labelText: 'Send a message'),
),
),
new StreamBuilder(
stream: channel.stream,
builder: (context, snapshot) {
//网络不通会走到这
if (snapshot.hasError) {
_text = "网络不通...";
} else if (snapshot.hasData) {
_text = "echo: "+snapshot.data;
}
return new Padding(
padding: const EdgeInsets.symmetric(vertical: 24.0),
child: new Text(_text),
);
},
)
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _sendMessage,
tooltip: 'Send message',
child: new Icon(Icons.send),
),
);
}
void _sendMessage() {
if (_controller.text.isNotEmpty) {
channel.sink.add(_controller.text);
}
}
@override
void dispose() {
channel.sink.close();
super.dispose();
}
}
细心的小伙伴可能已经发现了,这里面改动的只有一个东西。
就是从IOWebSocketChannel
到 HtmlWebSocketChannel
就这么简单。
然后一波flutter run -d chrome

网友评论