avoid_state_constructors
Flags State subclasses that have constructors with non-empty bodies or initializer lists. Initialization logic in State classes should live in initState(), not in the constructor, to respect the Flutter widget lifecycle.
Why use this rule
Section titled “Why use this rule”The State constructor runs before the framework has fully initialized the state object. At construction time, widget, context, and other framework-provided properties are not yet available. Placing logic in the constructor can lead to subtle bugs when that logic depends on the widget tree. Using initState() ensures all framework wiring is in place.
See also: State class | State.initState | Dart lint: no_logic_in_create_state
class _BadWidget1State extends State<BadWidget1> { late String _data;
// Constructor body should be empty — move logic to initState() _BadWidget1State() { _data = 'Hello'; }
@override Widget build(BuildContext context) => const SizedBox();}
class _BadWidget2State extends State<BadWidget2> { final String _data;
// Initializer list in State constructor — move logic to initState() _BadWidget2State() : _data = 'Hello';
@override Widget build(BuildContext context) => const SizedBox();}class _GoodWidgetState extends State<GoodWidget> { late String _data;
@override void initState() { super.initState(); _data = 'Hello'; }
@override Widget build(BuildContext context) => const SizedBox();}
// Empty constructor is fineclass _GoodWidget2State extends State<GoodWidget2> { _GoodWidget2State();
@override Widget build(BuildContext context) => const SizedBox();}Turning this rule off
Section titled “Turning this rule off”This rule is in the recommended preset, so it is on with
preset: recommended or preset: opinionated. Add it to preset: core with
avoid_state_constructors: true.
To turn it off:
rules: avoid_state_constructors: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Options
Section titled “Options”Projects with a state abstraction that does not extend Flutter’s State can
opt that base class into this rule:
many_lints: rules: avoid_state_constructors: state_base_classes: [AppState]rules: avoid_state_constructors: state_base_classes: [AppState]| Option | Type | Default | Description |
|---|---|---|---|
state_base_classes |
list of strings | [] |
Additional non-State base classes whose subclasses should be treated as state classes |
Related rules
Section titled “Related rules”prefer_immutable_state— Ensure classes named as state are annotated with @immutable.avoid_empty_setstate— Don’t call setState with an empty callback.avoid_inherited_widget_in_initstate— Don’t look up inherited widgets inside initState.avoid_late_context— Don’t read BuildContext in a late field initializer.