Skip to content

no_side_effects_in_build

Reports a side effect that runs while a widget is built. Create controllers, futures and streams once, in initState or a field of the State, and never call setState from build.

Tier
blocking
Scope
Flutter
Fix
none

Four kinds of side effect. Each violation says which one it is:

Kind The violation covers
A controller is created the name of the constructor: TextEditingController, TextEditingController.fromValue, ValueNotifier<int>
A future is started the name of the function or method that is called, the name of the constructor of Future, or the word async of a function literal that is called where it stands
A stream is made for a StreamBuilder the name of the method or function called, or of the constructor: watch, map, Stream.periodic
setState is called the word setState

A controller is a ChangeNotifier (TextEditingController, ScrollController, FocusNode, ValueNotifier, …), an AnimationController or a StreamController.

“While a widget is built” means:

  • the build method of a widget or State;
  • a function inside it that returns a widget, such as a builder callback;
  • a function literal called where it stands, () { … }();
  • a method of the class that build calls on the object itself, up to its first await.

It does not report:

  • a handler that runs later: onTap, onChanged, the callback of addPostFrameCallback;
  • a controller, future or stream created elsewhere that build only reads: TextField(controller: _controller), FutureBuilder(future: _future, …), stream: bloc.stream;
  • a controller or future created once under a condition and kept in a field: _future ??= load();, if (_controller == null) { _controller = TextEditingController(); }.

A setState call is reported under any condition.

The framework calls build whenever it needs the widget again: when its state changes, when a widget above it rebuilds, when the keyboard opens, on every frame of an animation. A controller created there loses what the user typed and is never released, a future starts its request again and puts a FutureBuilder back to waiting, and setState throws in a debug build or rebuilds without end. The first build works, so the defect does not show while you write the code.

Violating
class _ProfileState extends State<Profile> {
@override
Widget build(BuildContext context) {
final name = TextEditingController(text: widget.user.name);
return FutureBuilder<Orders>(
future: widget.repository.loadOrders(widget.user),
builder: (context, snapshot) => Column(
children: [
TextField(controller: name),
OrderList(snapshot.data),
],
),
);
}
}
Correctedboth are created once, kept in the State and released with it.
class _ProfileState extends State<Profile> {
late final _name = TextEditingController(text: widget.user.name);
late final _orders = widget.repository.loadOrders(widget.user);
@override
void dispose() {
_name.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FutureBuilder<Orders>(
future: _orders,
builder: (context, snapshot) => Column(
children: [
TextField(controller: _name),
OrderList(snapshot.data),
],
),
);
}
}

A setState that build calls to store a value it has just computed is replaced by using the value:

// Violating
setState(() => _total = _items.fold(0, _sum));
return Text('$_total');
// Corrected
final total = _items.fold(0, _sum);
return Text('$total');

Set under the assay: key of the project’s root analysis_options.yaml.

Rule parameter Default Effect
enabled true false switches the rule off for the whole project.
exclude [] Path globs where the rule is silent.
assay:
rules:
no_side_effects_in_build:
exclude: ["lib/legacy/**"]

Write why on the line directly above the suppression:

// The repository keeps the future of each id and gives the same one again.
// ignore: assay/no_side_effects_in_build
future: widget.repository.orders(widget.id),

A violation in a method that build calls is at the side effect in that method, not at the call in build, so the suppression goes there.

// ignore_for_file: assay/no_side_effects_in_build silences it in a whole file, and // ignore: no_side_effects_in_build without the prefix works too. See Suppressions.

All cases
  • A controller created in build is a new one at every rebuild. The text the user typed, the scroll position or the focus is gone, and the old controller is never released: its listeners, and what they reference, stay in memory.
  • A future started in build starts its work again at every rebuild: the request is sent again, the file read again. A FutureBuilder given a new future goes back to waiting, so the page flickers between the result and the progress indicator, and a rebuild that the result causes starts the next request.
  • setState in build asks for a rebuild while the build runs. The framework throws in a debug build; where it does not, the widget rebuilds without end.

So build must give the same widgets for the same input, and do nothing else. Code written by an AI coding agent has the defect often: FutureBuilder(future: load(), …) and TextField(controller: TextEditingController(text: value)) read well and run once without a visible fault.

That is the build method and what runs with it:

  • The build method: the method named build, returning a widget, of a class that extends Flutter’s Widget or State, or of a mixin on one of them. That includes a package’s widget class that builds with more than the context, build(BuildContext context, WidgetRef ref).
  • A function inside it that returns a widget: the builder callback of a Builder, a FutureBuilder or ListView.builder, the callback of map that turns each item into a widget, a local function such as Widget row(Item item) => ….
  • A function literal called where it stands, () { … }().
  • A method of the class that it calls on the object itself, _buildForm() or this._prepare(), and the methods that one calls in turn. Of a method that suspends at an await, only what comes before its first await runs with the build, the awaited call included. A setState after the await is the business of setstate_after_await.

Any other function inside build is only passed on: a button’s handler, onTap, onChanged, the callback of addPostFrameCallback. It runs later, and nothing in it is reported.

A controller is an object of one of these types, or of a subtype, created by a constructor call:

Type From
ChangeNotifier Flutter
AnimationController Flutter
StreamController dart:async

TextEditingController, ScrollController, PageController, TabController, FocusNode and ValueNotifier are change notifiers, and so is a class of the project that extends or mixes in ChangeNotifier.

A future is started by:

  • a call of a function, method or static method declared to return a Future: load(), repository.fetch(), Navigator.of(context).push(…), showDialog(…);
  • a call of a function held by a field, getter, parameter or local variable, whose type returns a Future: widget.onLoad(), widget.onLoad?.call();
  • a constructor of Future that runs something: Future(…), Future.delayed(…), Future.microtask(…), Future.sync(…);
  • an async function literal called where it stands: () async { … }(). Nothing inside it is reported besides.

A future with then, catchError or whenComplete called on it is reported once, at the call that starts it.

A stream is made for a StreamBuilder when the stream argument of Flutter’s StreamBuilder, or of a subclass, is a call or creation that is not constant and gives a Stream: stream: repository.watch(), stream: _stream.map(…), stream: Stream.periodic(…), stream: collection.snapshots(). At each rebuild the builder compares the stream with the one it had. A new one makes it drop its subscription, listen anew and show the waiting state or its initial data again, and a single-subscription source listened to twice throws. It is reported under any condition, since the builder takes it where it stands:

  • message: “This makes a new stream each time the widget is built, so the ‘StreamBuilder’ drops its subscription and listens anew at every rebuild, and loses what it showed.”
  • how to fix: “Make the stream once, in ‘initState’ or in a field of a State, and pass the field here.”

A setState call is a call of the setState of Flutter’s State on the state itself: setState(…), this.setState(…), super.setState(…).

  • a controller or future created elsewhere that build only reads: TextField(controller: _controller), FutureBuilder(future: _future, …), _controller.text;
  • a stream read from a variable, field or getter (stream: widget.stream, stream: bloc.stream, stream: _controller.stream), a constant stream, and a stream that a widget other than a StreamBuilder takes;
  • a future that is done and runs nothing: Future.value(…), Future.error(…);
  • a call whose declaration returns a type parameter, though it gives a future or stream: ref.watch(provider.future), context.read<Future<User>>(), cache.putIfAbsent(…);
  • a call declared to return FutureOr, or a subtype of Future such as the TickerFuture of controller.forward();
  • a controller or future that a condition decides on and that nothing uses where it stands (see below);
  • a side effect outside a build: in initState, in a handler method passed on as onTap: _submit, in a build of a class that is no widget, in a top-level function that returns a widget;
  • something else named setState, and a class named like a controller that is none of the types above;
  • anything in a package that does not use Flutter.

A controller or future is not reported when both of these hold.

1. Nothing uses it where it stands. It is assigned to a field or top-level variable, or to an entry of a list or map one of them holds (_controllers[index] ??= TextEditingController(), this._futures[id] ??= load()). Or it is a future nothing takes: a call that is a statement of its own, also with then and the like, and inside unawaited(…). The assignment’s value may be used further: in final field = _controllers[index] ??= TextEditingController(); the controller is still the one the map keeps.

Two more forms count as assigned:

  • One side of ?? is taken as the whole ??: in _controller ??= widget.controller ?? TextEditingController(); the new controller is what the field gets when none was handed in.
  • Set up in a local variable first, under a condition, then assigned by the same function to a field, a top-level variable or an entry of a collection one of them holds: final created = TextEditingController(); created.addListener(_changed); _controller = created; inside an if, or in a method called under a condition. The condition must decide on the creation: with the variable declared outside the if and assigned inside it, a controller is created at every build, and it is reported.

2. It stands under a condition, which is:

  • the value of a ??=, which is its own condition;
  • either branch of an if statement or a collection if;
  • a branch of a conditional expression or a case of a switch;
  • what follows an if statement that can leave the function with return or throw;
  • everything a method does when its call stands under a condition. A method called under a condition in one place and under none in another is read as called under none.

A method of the class is left to a condition the same way when its value is assigned to a field with ??= or under a condition, or its call is a statement of its own under a condition. Then these are left to that condition too:

  • what the method returns: its expression body, the value of a return, and a local variable it creates, sets up and returns;
  • everything an async method does: it is the work of the future the call started, which starts only when the condition holds.

A method reached this way in one place and another way elsewhere is read in the way that reports more.

@override
Widget build(BuildContext context) {
_future ??= widget.repository.load(); // not reported
if (_controller == null) {
_controller = TextEditingController(); // not reported
}
if (!_announced) {
_announced = true;
SemanticsService.announce(label, direction); // not reported
}
final note = _notes[widget.id] ??= TextEditingController(); // not reported
_name ??= widget.name ?? TextEditingController(); // not reported
if (_search == null) {
final search = TextEditingController(); // not reported
search.addListener(_changed);
_search = search;
}
return FutureBuilder<Items>(future: _future, builder: _items);
}

The same with methods of the class:

Future<Items> _load() async {
final items = await widget.repository.load(); // not reported
return items;
}
TextEditingController _create() {
final controller = TextEditingController(); // not reported
controller.addListener(_changed);
return controller;
}
Future<void> _start() async {
final items = await widget.repository.load(); // not reported
if (!mounted) return;
setState(() => _items = items); // not reported: after the await
}
@override
Widget build(BuildContext context) {
_future ??= _load();
_controller ??= _create();
if (!_started) {
_started = true;
_start();
}
return FutureBuilder<Items>(future: _future, builder: _items);
}

With FutureBuilder<Items>(future: _load(), …) in place of the field, _load() is reported, and so is the load() it awaits: the future is used where it stands, and is a new one at every build.

The rule does not read the condition. It takes it that the condition lets the code run once, or only when something changed, which is what such a condition is for.

A controller or future that is used where it stands is reported under any condition, because the widget gets a new one each time the condition holds:

if (snapshot.hasData) {
return FutureBuilder<Details>(
future: loadDetails(snapshot.data), // reported
builder: _details,
);
}
return Column(
children: [
if (editing) TextField(controller: TextEditingController()), // reported
],
);

A create-once is read only in the forms above: _future ??= load(); is one, while _future = _future ?? load(); and a test with && or || in place of an if, _ready || _prepare(), are not.

A call declared to return a Future is taken to start one, also where it gives the same future again, as a memoizer does: Future<Config> config() => _config ??= _read();.

A setState call is reported under any condition, since it throws whenever it runs during a build. That holds for a setState before the first await of an async method too, whatever its call was left to.