Invalid constant value.问题

阅读 62

2024-01-02

Invalid constant value.问题

在你的 _RecordDay 类中,你定义了一个 const 构造函数:

const _RecordDay(this.orientation);

但是在 build 方法中,你使用了这个构造函数:

RecordDay(orientation == Orientation.portrait),

这里的问题是,你在构造函数中使用了 const,但是在实际调用构造函数时,传递的参数使用了表达式 orientation == Orientation.portrait,这是一个非常量表达式,导致整个实例不再是 const

要解决这个问题,你可以考虑在构造函数中移除 const

_RecordDay(this.orientation);

然后在使用时,不再需要 const

RecordDay(orientation == Orientation.portrait),

这样就能避免 "Invalid constant value." 的错误。


如果你遇到了"A value of type 'Null' can't be assigned to a parameter of type 'bool' in a const constructor."的错误,说明在使用 const 构造函数时,传递的参数可能为 null

在 Dart 中,const 构造函数要求传递的参数不能为 null。如果你想在构造函数中接收 null 值,应该去掉构造函数前的 const 关键字。

以下是一个不使用 const 的例子:

class _RecordDay extends ConsumerWidget {
  final bool? orientation;

  // 构造函数
  const _RecordDay({required this.orientation});  

  // ... 其他部分
}

这里 bool? 表示 orientation 可以为 null。如果你不确定传递的参数是否为 null,可以使用这种方式来处理。


精彩评论(0)

0 0 举报