runStreamWithCallback method
Future<void>
runStreamWithCallback({
- required TuulOptions tuulOptions,
- required void onEvent(
- SseEvent event
- void onDone()?,
- void onError(
- Object error,
- StackTrace stackTrace
Initiates a streaming request using Server-Sent Events (SSE) and callbacks.
This is ideal for Flutter UIs where you want to update the state as
tokens arrive via onEvent.
tuulOptions: Configuration for the generation.onEvent: Called whenever a new SseEvent (like a token) is received.onDone: Called when the stream closes normally.onError: Called if the connection or parsing fails.
Implementation
Future<void> runStreamWithCallback({
required TuulOptions tuulOptions,
required void Function(SseEvent event) onEvent,
void Function()? onDone,
void Function(Object error, StackTrace stackTrace)? onError,
}) async {
tuulOptions.validate();
await client.sse(
"/generate",
method: 'POST',
headers: _headers(),
body: tuulOptions.toJson(),
onChunk: (chunk) {
try {
final decoded = jsonDecode(chunk);
if (decoded is Map<String, dynamic>) {
onEvent(SseEvent.fromJson(decoded));
}
} catch (_) {
// Ignore keep-alive / malformed chunks
}
},
onDone: onDone,
onError: onError,
);
}