Skip to main content

useStreamController

Creates a broadcast StreamController that lives across rebuilds and is closed automatically when the hook is disposed.

({void Function(String) onQueryChanged, String query}) useQueryStream() {
// Broadcast controller, closed automatically when the hook is disposed.
final controller = useStreamController<String>();

// De-duplicate the raw input stream and expose the latest value.
final latest = useStream(useMemoized(() => controller.stream.distinct()));

return (
// The View wires this to a text field; each call pushes onto the sink.
onQueryChanged: controller.sink.add,
query: latest.data ?? '',
);
}

Signature

StreamController<T> useStreamController<T>();

Returns a StreamController<T>.broadcast(). There are no parameters: the controller is created once, memoized for the lifetime of the hook, and close() is called on dispose.

Use cases

  • Turning imperative callbacks into a Stream you can then transform - debounce a search field, throttle scroll events, merge several inputs.
  • Bridging a non-reactive API into the stream hooks (useStream, useStreamSubscription).

Caveats

  • The controller is a broadcast controller, so it supports multiple listeners but does not buffer: events added before anyone listens are dropped, and a late listener sees only events from the moment it subscribes.

  • Do not call close() yourself - the hook owns the controller's lifecycle and closes it on dispose.

See also