1

我想使用 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连接有效,但此时我不知道该怎么做

4

1 回答 1

0

好的,我终于得到了解决方案,基本上我所做的是:

// socket.dart
  listenWSMessages(List<Object> result) {
    socketController.wsData.value = result[1]; // add .value
  }
// list_demo_controller.dart
class ListDemoController extends GetxController {
  WebSocket webSocket = WebSocket();
  var data = ''.obs; // create this variable
  @override
  void onInit() {
    super.onInit();
    webSocket.createWS();
    data = webSocket.socketController.wsData; // add this line
  }
}
// finally in list_demo.dart
class ListDemo extends StatelessWidget {
  final ListDemoController listDemoController = Get.put(ListDemoController());
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Obx(() => Text("${listDemoController.data}")), // add this line
    );
  }
}

字体:https ://pub.dev/packages/get

于 2020-10-09T18:45:40.413 回答