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

TSR*_*TSR 2 dart flutter

如何在 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);
Run Code Online (Sandbox Code Playgroud)

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

The method '<' was called on null.
Receiver: null
Run Code Online (Sandbox Code Playgroud)

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

Gui*_*lla 5

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

你打电话时:

backgroundItemCount = backgroundItemCount == null ? itemCount - 1 : backgroundItemCount
Run Code Online (Sandbox Code Playgroud)

您不会为收到的输入分配新值,您可能会将其保存到本地属性。您在上面一行中实际执行的操作是:

this.backgroundItemCount = backgroundItemCount == null ? itemCount - 1 : backgroundItemCount
Run Code Online (Sandbox Code Playgroud)

这就是断言失败的原因,因为它不检查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);
Run Code Online (Sandbox Code Playgroud)