DateTime 类参数应该是 const 但 DateTime 不支持此

Ian*_*ith 6 dart flutter flutter-dependencies

正如屏幕截图中所示,Flutter/Dart SDK 表示我的可选参数应该是 const。但 DateTime 库不支持 const 构造函数,如下面的 Github 链接所示。

除了不使用 DateTime 对象类型之外,我还需要做什么来解决这个问题?

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

在此输入图像描述

YoB*_*oBo 5

.now()命名构造函数不能是const.

您可以使用不同的参数名称,并在构造函数中使用 null-aware operator( ??) 对其进行分配,以使用 来添加默认值DateTime.now()

您可以在此处阅读有关 null 感知运算符的更多信息。

例子:

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

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
Run Code Online (Sandbox Code Playgroud)