如果在构造函数中不为null,则断言Dart



如何断言Dart构造函数中的参数是否为null?

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属性时。所以我的想法是,也许只有当这个属性不为空时,我们才应该断言。但我不知道怎么做

这是因为您没有断言CardStackCarousel属性(可能也有backgroundItemCount(,而是断言通过构造函数接收的参数,根据您的逻辑,该参数可能为null。

当你打电话时:

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

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

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

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

我将引用Dart官方文件中的一句话:

警告:初始值设定项的右侧无权访问这

在开发过程中,可以通过在初始值设定项列表中使用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);

相关内容

最新更新