Let's say I have several classes which extend an abstract class. Now I want to pass a default value to a function argument, where the type of the argument is the abstract class. Dart expects a const value, and I couldn't create a const constructor for an abstract class. How can I pass a default value of the abstract class?
Sample code is as following:
class Main {
late A objOfA;
Main({ A nObjOfA = const B() }); // <===== Error here
}
abstract class A {
abstract String name;
abstract int id;
}
class B extends A {
@override
String name = "B";
@override
int id = 1;
}
class C extends A {
@override
String name = "C";
@override
int id = 1;
}
Here, how can I pass a default value of nObjOfA
in the constructor of Main
?
CodePudding user response:
Dart expects a const value, and I couldn't create a const constructor for an abstract class.
There is no rule that you cannot create a const
constructor for an abstract class. Abstract classes can have constructors; you just can't call them directly to instantiate an abstract class. The following code is legal:
class Main {
A objOfA;
Main({this.objOfA = const B()});
}
abstract class A {
const A();
abstract final String name;
abstract final int id;
}
class B extends A {
const B();
@override
final String name = "B";
@override
final int id = 1;
}
class C extends A {
@override
String name = "C";
@override
int id = 1;
}
Note that I needed to add final
qualifiers since const
objects must be immutable. (Unrelated, but I also fixed the inappropriate use of the late
keyword.)
In general, there will be cases where you cannot create a const
constructor. If you want to use an instance of that type as a default argument in such cases, you can use null
as a default value and assign a non-const
value later.
CodePudding user response:
Try implements
instead of extends
and add a default constructor to class B