// import 'package:flutter/material.dart'; // class InformationPage extends StatefulWidget { // InformationPage({Key? key}) : super(key: key); // @override // State createState() => _InformationPageState(); // } // class _InformationPageState extends State { // @override // Widget build(BuildContext context) { // return Container( // child: Text('aa'), // ); // } // } import 'package:flutter/material.dart'; import 'package:web_socket_channel/io.dart'; class InformationPage extends StatefulWidget { InformationPage({Key? key}) : super(key: key); @override _InformationPageState createState() => _InformationPageState(); } class _InformationPageState extends State { TextEditingController _controller = TextEditingController(); late IOWebSocketChannel channel; String _text = ""; @override void initState() { // 创建websocket连接 channel = IOWebSocketChannel.connect( 'ws://101.35.117.69:9093/chat/api/chat/room/${1}'); } @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: [ Container( child: TextField( controller: _controller, decoration: InputDecoration(labelText: '发送消息'), ), ), StreamBuilder( stream: channel.stream, builder: (context, snapshot) { // 网络不通会走到这 if (snapshot.hasError) { _text = "网络不通..."; } else if (snapshot.hasData) { _text = "echo: ${snapshot.data}"; } return Padding( padding: const EdgeInsets.symmetric(vertical: 24.0), child: Text(_text), ); }, ) ], ), ), 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(); } }