3

Just getting started on Dart. DartPad says my code is not null-safe, but I don't see a way to initialize a "Point" without assigning a value to x and y, so it should be null-safe, shouldn't it?

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;
  }
}

Strangely enough, it works if I use what is outlined as "syntactic sugar". But doesn't that mean that the "common way" should also work?

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

class Point {
  double x;
  double y;

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

What am I missing here?

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
Sir Falk
  • 113
  • 5
  • Did you look at [this](https://dart.dev/tools/diagnostic-messages#not_initialized_non_nullable_instance_field) doc? – jabbson Aug 19 '21 at 14:19

3 Answers3

3

As said in Understanding null safety, you should to initialize non-nullable fields before constructor's body.

UPD: "Common way" in this case looks like this, using preconstructor:

class Point {
  double x;
  double y;

  Point(double x, double y) :
    this.x = x,
    this.y = y;
}
gierr7976
  • 46
  • 2
0

"Common way" will not work because Dart can't ensure that you will provide a non-nullable value to your variables. However, you can use the late keyword to tell Dart that you will.

class Point {
  late double x;
  late double y;

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

You can also mark x and y nullable if you don't want to use the late keyword:

class Point {
  double? x;
  double? y;

  Point(double x, double y) {
    this.x = x;
    this.y = y;
  }
}
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
0

In some cases, you can avoid null safety by adding ? into variables

class Point {
  double? x;
  double? y;

  Point(double x, double y) {
    this.x = x;
    this.y = y;
  }
}
ingmbk
  • 142
  • 1
  • 9
  • Hi, I think I've already provided this solution in [my answer](https://stackoverflow.com/a/68849874/6618622). – CopsOnRoad Aug 19 '21 at 15:10