Skip to content

widget_access_in_state_constructor

Reports a use of widget, context or setState in a State’s constructor, where they throw. Move the code to initState.

Tier
blocking
Scope
Flutter
Lowest preset
recommended
Fix
none

A use, in a constructor of a Flutter State, of what the state has only once it is mounted:

  • a read of its widget or its context, also through a lookup such as Theme.of(context);
  • a call or a tear-off of its setState, with no target or on this.

The violation covers the name that is used.

It does not report:

  • a use inside a function written in the constructor, since the function may run once the state is mounted;
  • a read of mounted, which gives false there and throws nothing.

The rule is silent in a package that does not use Flutter.

Flutter creates a state before it mounts it. The widget and the context are set afterwards, so each of these throws in the constructor. Put such code in initState, or in didChangeDependencies for what depends on the context.

Violating
class _ProfileState extends State<Profile> {
_ProfileState() {
title = widget.name;
}
String title = '';
}
Corrected
class _ProfileState extends State<Profile> {
String title = '';
@override
void initState() {
super.initState();
title = widget.name;
}
}

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.

Write why on the line directly above the suppression:

// Why this place is fine.
// ignore: assay/widget_access_in_state_constructor

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