flutter Text exception - expression is not a valid compile-time constant
Constants (i.e. const
) in Dart are compile-time, that is, they must not rely on the runtime of your application in anyway, and can only be simple side-effect free constructor invocations (i.e. const
constructors) or literals like strings, numbers, and lists/maps.
For example, this is a compile-time string:
const version = 'v1.0.0';
And I could use it below:
const Text(version)
Dart supports limited expressions as well, as compile-time constants:
const Text('My version is: $version')
However in your example, text
is not a compile-time constant.
Lets view this through a simpler example, called showMyName
:
Widget showMyName(String name) => const Text(name);
This will get an identical error to what you saw, because we're trying to create a compile-time constant Text
from a runtime provided value (the argument name
). Of course, we don't need Text
to be a compile-time constant. You can simply use new
:
Widget showMyName(String name) => new Text(name);
In future versions of Dart (with --preview-dart-2
), you can omit new
:
Widget showMyName(String name) => Text(name);