Skip to main content

pass-existing-stream-to-stream-builder

Warns when a newly created stream is passed to the StreamBuilder.

The stream must have been obtained earlier, e.g. during State.initState, State.didUpdateWidget, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the StreamBuilder. If the stream is created at the same time as the StreamBuilder, then every time the StreamBuilder's parent is rebuilt, the asynchronous task will be restarted.

Example

❌ Bad:

class SomeWidget extends Widget {

Widget build(BuildContext context) {
// LINT: Avoid passing a newly created stream to StreamBuilder.
// Try moving the stream to a variable and using it instead.
return StreamBuilder(
stream: getValue(),
builder: ...,
);
}

Stream<String> getValue() => Stream.fromIterable(['1', '2', '3']);
}

✅ Good:

class SomeWidget extends Widget {
final _local = getValue();


Widget build(BuildContext context) {
return StreamBuilder(
stream: _local,
builder: ...,
);
}

Stream<String> getValue() => Stream.fromIterable(['1', '2', '3']);
}

Additional Resources