Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing final fields from a subclass in Dart

Tags:

dart

This does not work:

abstract class Par {
  final int x;
}

class Sub extends Par {
  Sub(theX) {
    this.x = theX;
  }
}

I get an error in Par saying x must be initialized:

warning: The final variable 'x' must be initialized
warning: 'x' cannot be used as a setter, it is final
like image 721
gberger Avatar asked Jul 17 '15 21:07

gberger


People also ask

How do you initialize a dart function?

Either declare the function as static in your class or move it outside the class altogether. If the field isn't final (which for best practice, it should be, unless the field has to mutate), you can initialize it using a regular non-static method in the constructor body.

Can't be used as a setter because it's final?

This error happened because the text property of the TestModel class is final. Final objects arent meant to be changed in Flutter. to fix this problem you should go to the TestModel class and remove final from the text property.

How do you initialize a list in flutter?

initialize list in simple way using operator [] . create and fill a list with specified value using filled() constructor. create a list containing all specified itemsusing from() constructor. create a 'const' list using unmodifiable() constructor.


1 Answers

Give the superclass a constructor, and make the subclass call super:

abstract class Par {
  final int x;
  Par (int this.x) {}
}

class Sub extends Par {
  Sub(theX) : super(theX)
}

You can make the constructor private like so, because methods and fields starting with _ are private in Dart:

abstract class Par {
  final int x;
  Par._(int this.x) {}
}

class Sub extends Par {
  Sub(theX) : super._(theX)
}
like image 183
gberger Avatar answered Sep 20 '22 03:09

gberger