Home > Mobile >  Invalid Constant Value in Flutter/Dart Const Constructor
Invalid Constant Value in Flutter/Dart Const Constructor

Time:12-24

Getting "Invalid Constant Value" error in the below code, at "duration = Duration" assignment.

Removing the "const" before "TimeField.fromElapsed" resolves the "invalid constant value" error, but can someone help me understand why. (I'm new to using the const keyword in flutter, I read some articles on it and I think get the basics on it now, but still the below behaviour is confusing)

class TimeField extends StatelessWidget {
  final Duration duration;

  const TimeField({Key? key, required this.duration}) : super(key: key);

  const TimeField.fromElapsed({Key? key, required int elapsed})
      : duration = Duration(hours: elapsed, minutes: 0, seconds: 0),
        super(key: key);

CodePudding user response:

The first problem is that you have used a non constant Duration object to your widget's constant constructor so you need to convert it to:

 const TimeField.fromElapsed({Key? key, required int elapsed})
      : duration = const Duration(hours: elapsed, minutes: 0, seconds: 0),
        super(key: key);

But then you face another issue because you are passing a non constant value (the elapsed variable ) to the a const constructor of Duration class. so you should remove the const keywords.

CodePudding user response:

A const variable in Dart means a variable that can have its value defined as a compile time constant (a value that can have it's value computed at compile time, before the app runs, which would be runtime)

Examples of const values:

'any string'
10 * 20 // (or any other mathematical operation with const inputs)
const Duration(seconds: 1) // Any Object that has a const constructor and you pass it const arguments
etc.

The Duration object actually has a const Constructor, if you want to declare a const Duration there, you could. But at this point the compiler probably doesn't recognize the elapsed variable as a compile time constant because it can't infer it's value beforehand

  • Related