如何在 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
属性(property) - 可能有 backgroundItemCount
同样,您断言通过构造函数接收的参数,根据您的逻辑,该参数可能为 null。
当您调用时:
backgroundItemCount = backgroundItemCount == null ? itemCount - 1 : backgroundItemCount
您不会为收到的输入分配新值,您可能会将其保存到本地属性。您在上面一行中实际执行的操作是:
this.backgroundItemCount = backgroundItemCount == null ? itemCount - 1 : backgroundItemCount
这就是断言失败的原因,因为它没有检查 this.backgroundItemCount
,它检查通过构造函数接收的属性, backgroundItemCount
.
我会引用Dart official documentation中的一句话:
Warning: The right-hand side of an initializer does not have access to this.
...
During development, you can validate inputs by using assert in the initializer list.
这解释了为什么您无法检查 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);
关于flutter - Dart 断言构造函数中是否不为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63534920/