【自学Flutter】37 WebSockets的使用

37 WebSockets的使用

1.源代码
import 'package:flutter/material.dart';
import 'package:web_socket_channel/io.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  TextEditingController textEditingController = new TextEditingController();
  IOWebSocketChannel ioWebSocketChannel;
  String text = "";

  @override
  void initState() {
    ioWebSocketChannel = IOWebSocketChannel.connect('ws://echo.websocket.org');
  }

  void sendMessage() {
    if (textEditingController.text.isNotEmpty) {
      ioWebSocketChannel.sink.add(textEditingController.text);
    }
  }

  @override
  void dispose() {
    ioWebSocketChannel.sink.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("WebSocket的使用"),
        ),
        body: Padding(
          padding: EdgeInsets.all(20.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Form(
                child: TextFormField(
                  controller: textEditingController,
                  decoration: InputDecoration(labelText: '发送信息'),
                ),
              ),
              StreamBuilder(
                stream: ioWebSocketChannel.stream,
                builder: (context, snapshot) {
                  if (snapshot.hasError) {
                    text = "网络不通...";
                  } else if (snapshot.hasData) {
                    text = "返回获得的信息: "+snapshot.data;
                  }
                  return Padding(
                    padding: EdgeInsets.symmetric(vertical: 24.0),
                    child: Text(text),
                  );
                },
              ),
              RaisedButton(
                onPressed: sendMessage,
                child: Text("发送"),
              )
            ],
          ),
        ),
      ),
    );
  }
}
2.引用
  web_socket_channel: ^1.0.13

在这里插入图片描述

3.解释源代码
import 'package:flutter/material.dart';
import 'package:web_socket_channel/io.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  //声明 TextEditingController
  TextEditingController textEditingController = new TextEditingController();
  //创建 IOWebSocketChannel
  IOWebSocketChannel ioWebSocketChannel;
  //保存显示文本
  String text = "";

  //连接
  @override
  void initState() {
    ioWebSocketChannel = IOWebSocketChannel.connect('ws://echo.websocket.org');
  }

  //发送信息
  void sendMessage() {
    if (textEditingController.text.isNotEmpty) {
      ioWebSocketChannel.sink.add(textEditingController.text);
    }
  }

  //关闭
  @override
  void dispose() {
    ioWebSocketChannel.sink.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("WebSocket的使用"),
        ),
        body: Padding(
          padding: EdgeInsets.all(20.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Form(
                child: TextFormField(
                  controller: textEditingController,
                  decoration: InputDecoration(labelText: '发送信息'),
                ),
              ),
              StreamBuilder(
                stream: ioWebSocketChannel.stream,
                builder: (context, snapshot) {
                  if (snapshot.hasError) {
                    text = "网络不通...";
                  } else if (snapshot.hasData) {
                    text = "返回获得的信息: "+snapshot.data;
                  }
                  return Padding(
                    padding: EdgeInsets.symmetric(vertical: 24.0),
                    child: Text(text),
                  );
                },
              ),
              RaisedButton(
                onPressed: sendMessage,
                child: Text("发送"),
              )
            ],
          ),
        ),
      ),
    );
  }
}
4.效果图

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值