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

标签 flutter 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属性(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/

相关文章:

dart - Dart 继承进度

dart - Material Flutter 应用源码

flutter - Flutter 中可以有不同的 Button 样式吗?

Flutter - 参数类型 'String?' 无法分配给参数类型 'String'

android - 是否可以自定义 Flutter Webview 错误消息?

geometry - 如何使用 Flutter 的 PhysicalModel 制作圆形边框?

flutter - 从 Flutter 中的 Scaffold AppBar 中删除阴影?

dart - 如何在Dart中创建服务器端模板,在其中可以为每个页面设置不同的&lt;title/>?

dart - Dart错误:一个相等表达式不能是另一个相等表达式的操作数

json - 未处理的异常 : type '(dynamic) => Welcome' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform'