onClose method
Called when the WebSocket connection is closed.
The closeCode
and closeReason
provide details about why the connection
was closed. Implementations should update their connection state and determine
whether reconnection is appropriate based on the close reason.
Implementation
@override
void onClose([int? closeCode, String? closeReason]) {
final source = switch (connectionState.value) {
// If we were already disconnecting, keep the caller-provided source.
Disconnecting(:final source) => source,
// Any active state that wasn’t user/system initiated becomes server initiated.
Connecting() || Authenticating() || Connected() => ServerInitiated(
error: WebSocketEngineException(
code: closeCode,
reason: closeReason,
),
),
// Not meaningful to transition from these; just log and bail.
Initialized() || Disconnected() => null,
};
if (source == null) return;
// Update the connection state to 'disconnected' with the source.
_connectionState = WebSocketConnectionState.disconnected(source: source);
}