for_ in_ with_ const_ variable
A for-in loop variable can't be a 'const'.
Description
#
The analyzer produces this diagnostic when the loop variable declared in a
for-in loop is declared to be a
const
. The variable can't be a
const
because the value can't be computed at compile time.
Example
#
The following code produces this diagnostic because the loop variable
x
is declared to be a
const
:
void f() {
for (const x in [0, 1, 2]) {
print(x);
}
}
Common fixes
#
If there's a type annotation, then remove the
const
modifier from the
declaration.
If there's no type, then replace the
const
modifier with
final
,
var
,
or a type annotation:
void f() {
for (final x in [0, 1, 2]) {
print(x);
}
}
Unless stated otherwise, the documentation on this site reflects Dart 3.9.2. Page last updated on 2025-9-1. View source or report an issue.