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
What it reports
Section titled “What it reports”A use, in a constructor of a Flutter State, of what the state has only once it is mounted:
- a read of its
widgetor itscontext, also through a lookup such asTheme.of(context); - a call or a tear-off of its
setState, with no target or onthis.
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 givesfalsethere 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.
Example
Section titled “Example”class _ProfileState extends State<Profile> { _ProfileState() { title = widget.name; }
String title = '';}class _ProfileState extends State<Profile> { String title = '';
@override void initState() { super.initState(); title = widget.name; }}Rule parameters
Section titled “Rule parameters”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. |
Suppressing it
Section titled “Suppressing it”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.