【问题标题】:The argument type 'double?' can't be assigned to the parameter type 'double' [duplicate]参数类型“双?”不能分配给参数类型“双”[重复]
【发布时间】:2021-08-06 11:57:34
【问题描述】:

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

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 或使用它的值。这行有什么问题?

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

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

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

      angle: rotationAngle == null ? 0.0 : rotationAngle!
      

      【讨论】:

        【解决方案3】:

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

        试试这个

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-09-30
          • 2021-10-03
          • 2021-11-23
          • 2021-06-27
          • 2021-07-20
          • 2021-01-05
          • 2021-11-11
          相关资源
          最近更新 更多