how to display a websocket data in flutter with getx

2.6k views Asked by At

I want to display data realtime on ListDemo widget with the socket value using getx, but I having trouble to implement

// 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;
}

my widget:

class ListDemo extends StatelessWidget {
  final ListDemoController listDemoController = Get.put(ListDemoController());
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text('display data here'),
    );
  }
}

widget controller:

class ListDemoController extends GetxController {
  WebSocket webSocket = WebSocket(); // create a websocket
  @override
  void onInit() {
    super.onInit();
    webSocket.createWS(); // start websocket
  }
}

the websocket connection works, but at this point i dont know what to do

1

There are 1 answers

1
Igor On

ok, i finally get the solution, basically what i made is:

// 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
    );
  }
}

font: https://pub.dev/packages/get