我正在尝试将数据从API端点获取到我的Flutter应用中。我可以使用http请求来执行此操作,但是只要有更新数据库就可以接收更改。我发现这可以通过web_socket_channel来完成。
到目前为止,我已经尝试过
final WebSocketChannel channel = IOWebSocketChannel.connect("ws://127.0.0.1:3306/codeishweb/getData.php");
// In the StreamBuilder
StreamBuilder(
strema: channel.stream,
builder:(context, snapshot){
return Center(child:Text(snapshot.hasData? snapshot.data: "nothing available"));
}
);
这不起作用,并且我还收到错误消息Unsupported operation: Platform._version
。
我该如何实现自己想要实现的目标。预先感谢。
答案 0 :(得分:1)
您需要具有WebSocket服务器。如果您需要确保代码可以正常工作,请使用doc({http://www.websocket.org/echo.html)
中提供的服务器。连接到websocket.org提供的测试服务器。服务器发回与您发送给它的相同消息。此食谱使用以下步骤:
您可以使用的演示(flutter cookbook中可用)
import 'package:flutter/foundation.dart';
import 'package:web_socket_channel/io.dart';
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = 'WebSocket Demo';
return MaterialApp(
title: title,
home: MyHomePage(
title: title,
channel: IOWebSocketChannel.connect('ws://echo.websocket.org'),
),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
final WebSocketChannel channel;
MyHomePage({Key key, @required this.title, @required this.channel})
: super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _controller = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
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: widget.channel.stream,
builder: (context, snapshot) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 24.0),
child: Text(snapshot.hasData ? '${snapshot.data}' : ''),
);
},
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _sendMessage,
tooltip: 'Send message',
child: Icon(Icons.send),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
void _sendMessage() {
if (_controller.text.isNotEmpty) {
widget.channel.sink.add(_controller.text);
}
}
@override
void dispose() {
widget.channel.sink.close();
super.dispose();
}
}
These all details are available here with sample code。
如果您的服务器不是websoket服务器,则可能会有所帮助:
How to create websockets server in PHP
https://www.twilio.com/blog/create-php-websocket-server-build-real-time-even-driven-application