繁体   English   中英

Dart 在构造函数中断言如果不是 null

[英]Dart assert if not null in constructor

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

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

你打电话的时候:

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

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

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

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

引用Dart官方文档中的一句话:

警告:初始化程序的右侧无法访问它。

...

在开发期间,您可以通过在初始化列表中使用断言来验证输入。

这解释了为什么你不能检查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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM