【问题标题】:Constructor doesn't satisfy null safety in Dart [duplicate]Dart 中的构造函数不满足 null 安全性 [重复]
【发布时间】:2021-10-21 06:15:14
【问题描述】:

刚开始使用 Dart。 DartPad 说我的代码不是空安全的,但我看不到在不为 x 和 y 赋值的情况下初始化“点”的方法,所以它应该是空安全的,不是吗?

void main(){
  Point p = new Point(1.0,2.0);
  print(p.x);
}

class Point {
  double x;
  double y;

  Point(double x, double y) {
    this.x = x;
    this.y = y;
  }
}

奇怪的是,如果我使用概述为“语法糖”的内容,它就会起作用。但这不是说“通用方式”也应该有效吗?

void main(){
  Point p = new Point(1.0,2.0);
  print(p.x);
}

class Point {
  double x;
  double y;

  Point(this.x, this.y) {}
}

我在这里错过了什么?

【问题讨论】:

  • 你看过this doc吗?

标签: flutter dart dart-null-safety


【解决方案1】:

正如Understanding null safety 中所说,您应该在构造函数的主体之前初始化不可为空的字段。

更新: 在这种情况下,“通用方式”看起来像这样,使用 preconstructor

class Point {
  double x;
  double y;

  Point(double x, double y) :
    this.x = x,
    this.y = y;
}

【讨论】:

    【解决方案2】:

    "Common way" 将不起作用,因为 Dart 无法确保您将为变量提供不可为空的值。但是,你可以使用 late 关键字告诉 Dart 你会的。

    class Point {
      late double x;
      late double y;
    
      Point(double x, double y) {
        this.x = x;
        this.y = y;
      }
    }
    

    如果您不想使用late 关键字,也可以将xy 标记为可空:

    class Point {
      double? x;
      double? y;
    
      Point(double x, double y) {
        this.x = x;
        this.y = y;
      }
    }
    

    【讨论】:

      【解决方案3】:

      在某些情况下,您可以通过添加 ?变量

      class Point {
        double? x;
        double? y;
      
        Point(double x, double y) {
          this.x = x;
          this.y = y;
        }
      }
      

      【讨论】:

      • 嗨,我想我已经在my answer 中提供了这个解决方案。
      猜你喜欢
      • 2021-09-24
      • 2021-11-27
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多