美文网首页
Flutter Web 使用 webSocket

Flutter Web 使用 webSocket

作者: 尤先森 | 来源:发表于2020-05-19 16:34 被阅读0次

最近在折腾flutter web的相关内容,发现网上相关资源比较少。
(本来还想试试用tcp socket,才知道web并不支持这玩意。。。最后只能选webSocket)

找了好久,遇到了各种问题,确实,flutte web 现在还不是很成熟,但是还是让我发现了支持webSocket的pub包(绕来绕去,还是绕到原来的地方)

web_socket_channel 简介的最底部发现了。

image.png

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();
  }
}

细心的小伙伴可能已经发现了,这里面改动的只有一个东西。
就是从IOWebSocketChannelHtmlWebSocketChannel 就这么简单。

然后一波flutter run -d chrome

image.png

相关文章

网友评论

      本文标题:Flutter Web 使用 webSocket

      本文链接:https://www.haomeiwen.com/subject/lobbohtx.html