DateTime class parameter should be const but DateTime does not support this

Viewed 4252

As seen in the screen shot the Flutter/Dart SDK is saying my optional parameter should be const. But the DateTime library does not support const constructors as seen in the Github link below.

What am I expected to do here to fix this besides not use a DateTime object type for this?

https://github.com/dart-lang/sdk/issues/17014

enter image description here

1 Answers

.now() named constructor can't be const.

You can use different parameter name and assign it in the constructor with null-aware operator(??) to add the default value with DateTime.now().

You can read more about the null-aware operator here.

Example:

class ExamlpeWidget extends StatelessWidget {
  final DateTime creationDate;
  
  ExamlpeWidget({
    DateTime creationDateTime,
  }) : creationDate = creationDateTime ?? DateTime.now();

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
Related