A generator separates a sequence’s production from its consumption. Use a synchronous iterable for immediate computed values and an asynchronous stream for events over time. The consumer decides how much of the sequence it needs.
Worked example
Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.
Iterable<int> batchNumbers(int count) sync* {
for (var number = 1; number <= count; number++) {
yield number;
}
}
Stream<String> dispatchLabels(int count) async* {
for (final batch in batchNumbers(count)) {
yield 'Dispatch batch $batch';
}
}
Future<void> main() async {
print(batchNumbers(5).take(2).join(', '));
await for (final label in dispatchLabels(3)) {
print(label);
}
}Follow the data and control flow
The sync generator describes numbers without building an intermediate list. take consumes only the first two for that traversal. The async generator emits labels through a stream and finishes when its loop finishes. yield* can delegate a compatible sequence instead of manually forwarding each value.
Stream transformations can filter or map events before the final consumer. Keep ordering, backpressure and cancellation expectations explicit when adapting a real file or socket source.
A mistake to avoid
A generator body may run later than the function call that created the iterable or stream. Do not assume its side effects happened immediately. Long synchronous work inside async* still blocks the current isolate; emitting a stream does not make CPU processing parallel.
Practice and verification
Reject a negative count, then add a filter selecting even batch numbers. Stop the async consumer early and add a finally block to observe cleanup. Explain the difference between a lazy generator and a prebuilt list containing the same values.