Dart在构造函数中断言是否不为null

时间:2020-08-22 10:03:40

标签: flutter dart

如何在Dart构造函数中断言参数是否为空?

const CardStackCarousel({
    Key key,
    this.itemBuilder,
    this.itemCount,
    int backgroundItemCount,
    this.controller,
    this.offsetAboveBackcards: 10.0,
    this.minScale: 0.8,
    this.verticalAxis: false,
  })  : backgroundItemCount = backgroundItemCount == null ? itemCount - 1 : backgroundItemCount,
        assert(backgroundItemCount < itemCount, 'background item must be less than itemCount'),
        super(key: key);

使用上面的代码,我得到一个错误:

The method '<' was called on null.
Receiver: null

当用户未指定backgroundItemCount属性时。所以我的想法是,我们只能在此属性不为null时断言。但是我不知道该怎么做

1 个答案:

答案 0 :(得分:2)

这是因为您不是在声明CardStackCarousel属性-可能也有一个backgroundItemCount-是在声明您通过构造函数接收的参数,您的逻辑,可以为空。

致电时

backgroundItemCount = backgroundItemCount == null ? itemCount - 1 : backgroundItemCount

您没有为接收到的输入分配新值,您可能会将其保存到本地属性。您在上一行中实际上在做什么:

this.backgroundItemCount = backgroundItemCount == null ? itemCount - 1 : backgroundItemCount

这就是断言失败的原因,因为它不检查this.backgroundItemCount,而是检查通过构造函数backgroundItemCount接收的属性。

我会引用Dart official documentation中的一个短语:

警告:初始化器的右侧无权访问 这个。

...

在开发过程中,您可以通过使用初始化列表中的assert来验证输入。

其中解释了为什么您无法检查this的原因,因为它仍在“静态”验证您的输入-在右侧评估时,它还没有实例。


如果您仍然需要确保backgroundItemCount < itemCount,则只需使用assert(backgroundItemCount == null || backgroundItemCount < itemCount, 'If background item is supplied, it must be less than itemCount')

像这样:

const CardStackCarousel({
    Key key,
    this.itemBuilder,
    this.itemCount,
    int backgroundItemCount,
    this.controller,
    this.offsetAboveBackcards: 10.0,
    this.minScale: 0.8,
    this.verticalAxis: false,
  })  : backgroundItemCount = backgroundItemCount == null ? itemCount - 1 : backgroundItemCount,
        assert(backgroundItemCount == null || backgroundItemCount < itemCount, 'If background item is supplied, it must be less than itemCount'),
        super(key: key);