Skip to content

avoid_state_constructors

v0.4.0WarningFixConfigurableState Management

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.

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 fine
class _GoodWidget2State extends State<GoodWidget2> {
_GoodWidget2State();
@override
Widget build(BuildContext context) => const SizedBox();
}

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:

many_lints.yaml
rules:
avoid_state_constructors: false

To keep the rule on but skip certain paths, use per-rule exclude.

Projects with a state abstraction that does not extend Flutter’s State can opt that base class into this rule:

analysis_options.yaml
many_lints:
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