connect method Null safety

Future<WebSocketChannel?> connect(
  1. {Duration? timeout}
)

Connects the WebSocket. timeout is optional.

Implementation

Future<WebSocketChannel?> connect({Duration? timeout}) async {
  if (timeout != null) {
    var c = Completer<WebSocketChannel>();
    late Timer timer;

    timer = Timer(timeout, () {
      if (!c.isCompleted) {
        if (timer.isActive) timer.cancel();
        c.completeError(TimeoutException(
            'WebSocket connection exceeded timeout of ${timeout.inMilliseconds} ms',
            timeout));
      }
    });

    scheduleMicrotask(() {
      getConnectedWebSocket().then((socket) {
        if (!c.isCompleted) {
          if (timer.isActive) timer.cancel();

          while (_queue.isNotEmpty) {
            var action = _queue.removeFirst();
            socket.sink.add(serialize(action));
          }

          c.complete(socket);
        }
      }).catchError((e, StackTrace st) {
        if (!c.isCompleted) {
          if (timer.isActive) {
            timer.cancel();
          }

          // TODO: Re-evaluate this error
          var obj = 'Error';
          c.completeError(obj, st);
        }
      });
    });

    return await c.future.then((socket) {
      _socket = socket;
      listen();

      return _socket;
    });
  } else {
    _socket = await getConnectedWebSocket();
    listen();
    return _socket;
  }
}