dartflutter

Invalid Constant Value using variable as parameter


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?


Solution

  • 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 indicator for a widget that never updates as it will get evaluated at compile time and only once. Hence, every parameter passed to it has to be constant as well.

    double textSize = 10.04;
    // ...
    child: Text('Calculate Client Fees', style: TextStyle(fontSize: textSize))
    

    This means the widget will never rebuild due to an update of its parameters but only due to internal state changes.

    Read more about it in this article.