Home > database >  Dart error, This constructor should initialize field 'x' because its type 'int'
Dart error, This constructor should initialize field 'x' because its type 'int'

Time:01-09

I'm new to Dart. This is my code:

class Point {
  int x;
  int y;

  Point(this.x, this.y);

  Point.same(int i) {
    x = i;
    y = i;
  }
}

main() {}

I got this error when running it.

bin/dart1.dart:7:3: Error: This constructor should initialize field 'x' because its type 'int' doesn't allow null.
  Point.same(int i) {
  ^
bin/dart1.dart:2:7: Context: 'x' is defined here.
  int x;
      ^
bin/dart1.dart:7:3: Error: This constructor should initialize field 'y' because its type 'int' doesn't allow null.
  Point.same(int i) {
  ^
bin/dart1.dart:3:7: Context: 'y' is defined here.
  int y;
      ^

As I understand, the parameter int i of Point.same() is non-nullable, and I use it to initialize x and y (x = i; y = i;). Why it still asks me to initialize x and y? I even tried the following code and still got the same error:

class Point {
  int x;
  int y;

  Point(this.x, this.y);

  Point.same() {
    x = 3;
    y = 3;
  }
}

main() {}

CodePudding user response:

When initializing fields from a constructor without constructor parameters, use the initializer list. It runs prior to the constructor body and allow you to initialize final and non-nullable variables without marking them late.

class Point {
  int x;
  int y;

  Point(this.x, this.y);

  Point.same(int i) :
    x = i,
    y = i;
}

main() {}
  •  Tags:  
  • Related