assignment_ to_ const
Constant variables can't be assigned a value after initialization.
Description
#
The analyzer produces this diagnostic when it finds an assignment to a
top-level variable, a static field, or a local variable that has the
const
modifier. The value of a compile-time constant can't be changed at
runtime.
Example
#
The following code produces this diagnostic because
c
is being assigned a
value even though it has the
const
modifier:
const c = 0;
void f() {
c = 1;
print(c);
}
Common fixes
#If the variable must be assignable, then remove the const
modifier:
var c = 0;
void f() {
c = 1;
print(c);
}
If the constant shouldn't be changed, then either remove the assignment or use a local variable in place of references to the constant:
const c = 0;
void f() {
var v = 1;
print(v);
}
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.