Invalid Constant Value using variable as parameter
DartFlutterDart Problem Overview
var textSize = 10.0;
// or
double textSize = 10.0;
into Text
Widget of Flutter
child: const Text('Calculate Client Fees',
style: TextStyle(fontSize: textSize),)
Here it is giving error
>Invalid Constant Value
Do we have to compulsory use const
value? Why can not we use var
or double
?
Dart Solutions
Solution 1 - Dart
You are declaring your Text
widget as a const
, which requires all of its children to be const
as well. If you want to fix this, you should not use a const
Text
widget in this case as you want to pass a non-const variable.
The reason for this is that Flutter uses the const
keyword as an idicator for a widget to never rebuild as it will get evaluated at compile time and only once. Hence, every part of it has to be constant as well.
double textSize = 10.04;
// ...
child: Text('Calculate Client Fees', style: TextStyle(fontSize: textSize))
Read more about it in this article.
Solution 2 - Dart
Don't use the const keyword if you are not using fixed values.
Solution 3 - Dart
As @creativecreatorormaybenot said you are using const Text()
which is why you have to have a const
value there.
You can either use
const double textSize = 10.0;
or
const textSize = 10.0;
Just like this case.
Padding(
padding: const EdgeInsets.all(value), // this value has to be a `const` because our padding: is marked const
child: Text("HI there"),
);
Padding(
padding: EdgeInsets.all(10), // any double value
child: Text("HI there"),
);
Solution 4 - Dart
In dart when you pass something as a parameter in a const constructor, the compiler makes sure that the value set as default is not changed during the execution of the code.
Hence, the Invalid constant value warning.
To resolve this issue you should remove the const keyword from the in front of the Text.
Solution 5 - Dart
child: const Text('Calculate Client Fees',
style: TextStyle(fontSize: textSize),)
should be:
child: Text('Calculate Client Fees',
style: TextStyle(fontSize: textSize),)
Solution 6 - Dart
You should remove the keywords const
When it is used, it put the widget into the cache.
And you can't wait for a value into your widget and put the widget again as a constance. When you want to do that, you should not put your widget constant.
So do that:
double textSize = 10.0;
child: Text('Calculate Client Fees', style: TextStyle(fontSize: textSize),)
Solution 7 - Dart
if you want to use the var
or double textSize = 10.0;
then the text widget must not be a const. remove the const
before the Text()
child: Text('Calculate Client Fees', style: TextStyle(fontSize: textSize),)