参数类型“double?”不能分配给参数类型 'double'

时间:2021-05-17 08:04:44

标签: flutter dart

我有这个类,尝试插入图标并可能根据旋转角度在容器内旋转它。

class ReusableCardIconLayout extends StatelessWidget {
  final double? rotationAngle;

  ReusableCardIconLayout({this.rotationAngle});

  @override
  Widget build(BuildContext context) {
    return Expanded(
      flex: 2,
      child: Transform.rotate(
        angle: rotationAngle == null ? 0.0 : rotationAngle,
      ),
    );
  }
}

其中,rotationAngle 是可选的,因此我将其设为可空。

现在,线

angle: rotationAngle == null? 0.0 : rotationAngle,

显示错误“参数类型'double?'不能分配给参数类型 'double'"。

为什么会出现这样的错误?我已经检查过它是否为空。如果是,则给出默认值 0.0 或使用它的值。这行有什么问题?

有没有办法像上面那样使用三元运算符来解决它?

是否给默认参数值只剩下选项?

3 个答案:

答案 0 :(得分:1)

您可以使用空合并运算符 (??):

child: Transform.rotate(
  angle: rotationAngle ?? 0.0,
),

如果 rotationAngle != null,将使用 rotationAngle 值,否则 - 0.0。

答案 1 :(得分:0)

rotationAngle 的类型可为空,因此您应该使用 ! 来使用它。
例如:

angle: rotationAngle == null ? 0.0 : rotationAngle!

答案 2 :(得分:0)

我认为您已经将项目移至 NULLSAFE

试试这个

angle: rotationAngle == null? 0.0 : rotationAngle!,