Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid Constant Value using variable as parameter

Tags:

flutter

dart

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?

like image 508
Gaurang Goda Avatar asked Apr 11 '19 15:04

Gaurang Goda


4 Answers

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.

like image 110
creativecreatorormaybenot Avatar answered Nov 14 '22 02:11

creativecreatorormaybenot


Don't use the const keyword if you are not using fixed values.

like image 31
Muhammad Umair Saqib Avatar answered Nov 14 '22 01:11

Muhammad Umair Saqib


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.

like image 11
Delicia Fernandes Avatar answered Nov 14 '22 03:11

Delicia Fernandes


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"),
);
like image 10
CopsOnRoad Avatar answered Nov 14 '22 02:11

CopsOnRoad