6

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

Ian Smith
  • 879
  • 1
  • 12
  • 23
  • This is OK. Since DateTime.now() gives current time. and obviously having it as const doesn't make sense, as time changes every fraction. – Nikhil Badyal Apr 17 '21 at 05:38
  • You can use my [const_date_time](https://pub.dev/packages/const_date_time) package to achieve this. ```dart import 'package:const_date_time/const_date_time.dart'; class MyClass { const MyClass({ this.date = const ConstDateTime(0), }); final DateTime date; } ``` – Westy92 Oct 28 '22 at 06:18

1 Answers1

5

.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();
  }
}
YoBo
  • 2,292
  • 3
  • 9
  • 25
  • Thanks, do you mind clarifying what `??` stands for in the answer for others? It's basically an OR operator from what I can understand when dealing with NULL values. – Ian Smith Apr 17 '21 at 04:07
  • 1
    @IanSmith It's null check operator. Before assigning to creationdate. It says `creationDateTime` a question, ARE YOU NULL ? If it gives the answer as NO. Then the leftt side operand `creationDateTime` is assigned otherwise the right side `DateTime.now()` is assigned to creationDate. – Nikhil Badyal Apr 17 '21 at 05:41
  • If `creationDateTime` is not null, it will assign it to `creationDate` else it will use `DateTime.now()`. I updated my answer with a link for article explaining what it does. – YoBo Apr 17 '21 at 06:00
  • Getting error "All final variables must be initialized, but 'creationDate' isn't. Try adding an initializer for the field." – Kamlesh Jun 15 '21 at 12:59