createState does more than return a new State instance
ID |
dart.correctness.no_logic_in_create_state |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Framework Misuse |
Language |
Dart |
Description
Reports a createState implementation whose body is more than a single return of a newly built State object - initialisation of the returned state, logging, registration in a cache, or any other statement executed before the return.
Rationale
The framework decides when and how often createState runs. It is called every time the element for the widget is inflated, which happens again whenever the widget moves in the tree or its key changes, and the result is expected to be a fresh, unconfigured State. Work placed there therefore runs an unpredictable number of times and at a point where the state has no context, no widget and no mounted element yet. Configuration copied from the widget into the state at this moment also goes stale silently: the framework reuses the same State across widget rebuilds, so the values are never refreshed.
The following code illustrates the pattern detected by this rule:
class Seeded extends StatefulWidget {
final int seed;
Seeded(this.seed);
// FLAGGED: createState does more than return a new State instance
@override
State<Seeded> createState() {
final state = _SeededState();
state.seed = seed;
return state;
}
}
Remediation
Make createState a single return _MyWidgetState();. Move initialisation that depends on the widget into initState, which runs once with widget and context available, and recompute values that follow the widget in didUpdateWidget. Read configuration through widget.field rather than copying it into the state.