request<R> method
Send a typed request and await the response with timeout protection.
Perfect for request/reply patterns with background isolates. Creates a dedicated reply port, sends the request, and waits for exactly one response. Handles timeouts and error payloads automatically.
Parameters:
command: The command string for the worker to processdata: Optional data payload to include with the requesttimeout: Maximum time to wait for a response (default: 3 seconds)
Usage: {@tool snippet example/isolate_example.dart} {@end-tool}
Implementation
Future<R> request<R>(
String command, {
Map<String, Object?>? data,
Duration timeout = const Duration(seconds: 3),
}) async {
final completer = Completer<Object?>();
final reply = RawReceivePort();
reply.handler = (Object? msg) {
if (completer.isCompleted) return;
completer.complete(msg);
};
sendCmd(command, data: {...?data, 'reply': reply.sendPort});
try {
final obj = await completer.future.timeout(
timeout,
onTimeout: () {
throw TimeoutException(
'request("$command") timed out after $timeout',
);
},
);
if (obj is Map && obj['error'] != null) {
throw StateError('request("$command") failed: ${obj['error']}');
}
try {
return obj as R;
} on TypeError {
throw StateError(
'request("$command") returned incompatible type: ${obj.runtimeType} expected: $R',
);
}
} finally {
reply.close();
}
}