如何使用getx在flutter中显示websocket数据

时间:2020-10-09 17:55:18

标签: flutter websocket flutter-get

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

1 个答案:

答案 0 :(得分: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