Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dart error, This constructor should initialize field 'x' because its type 'int' doesn't allow null

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Point {
  int x;
  int y;

  Point(this.x, this.y);

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

main() {}

>Solution :

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() {}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading