我想使用 getx 在带有套接字值的 ListDemo 小部件上实时显示数据,但我无法实现
// socket.dart
class WebSocket {
final hubConnection = HubConnectionBuilder().withUrl(EnvironmentHml.socketUrlFake).build();
SocketController socketController = Get.put(SocketController());
createWS() async {
await hubConnection.start();
hubConnection.on("ReceiveMessage", listenWSMessages);
}
listenWSMessages(List<Object> result) { // simple ws listener
socketController.wsData = result[1];
}
}
// socket_controller.dart
class SocketController extends GetxController {
var wsData = ''.obs;
}
我的小部件:
class ListDemo extends StatelessWidget {
final ListDemoController listDemoController = Get.put(ListDemoController());
@override
Widget build(BuildContext context) {
return Container(
child: Text('display data here'),
);
}
}
小部件控制器:
class ListDemoController extends GetxController {
WebSocket webSocket = WebSocket(); // create a websocket
@override
void onInit() {
super.onInit();
webSocket.createWS(); // start websocket
}
}
websocket连接有效,但此时我不知道该怎么做