赞
踩
-
- import 'package:flutter/material.dart';
- import 'package:web_socket_channel/io.dart';
-
- class SocketPage extends StatefulWidget {
- const SocketPage({Key? key}) : super(key: key);
-
- @override
- State<StatefulWidget> createState() => _SocketState();
-
- }
-
- class _SocketState extends State<SocketPage> {
-
- final TextEditingController _controller = TextEditingController();
- late IOWebSocketChannel channel;
-
- @override
- void initState() {
- channel = IOWebSocketChannel.connect('wss://echo.websocket.events');
- }
-
-
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title: Text("WebSocket(内容回显)"),
- ),
- body: Padding(
- padding: const EdgeInsets.all(20.0),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: <Widget>[
- Form(
- child: TextFormField(
- controller: _controller,
- decoration: InputDecoration(labelText: 'Send a message'),
- ),
- ),
- StreamBuilder(
- stream: channel.stream,
- builder: (context, snapshot) {
- return Text(snapshot.hasData ? '${snapshot.data}' : '');
- },
- )
- ],
- ),
- ),
- floatingActionButton: FloatingActionButton(
- onPressed: _sendMessage,
- tooltip: 'Send message',
- child: Icon(Icons.send),
- ),
- );
- }
-
- void _sendMessage() {
- if (_controller.text.isNotEmpty) {
- channel.sink.add(_controller.text);
- }
- }
-
- @override
- void dispose() {
- channel.sink.close();
- super.dispose();
- }
- }

赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。