I made this abstract class
abstract class API {
//* ---- abstract fields , Methods ---- *//
int? timeOut;
int? getTimeOut();
}
then i implemented it with a class and made the field final
class GetData implements API {
@override
final int? timeOut;
GetData(int? ta) : timeOut = ta;
@override
int? getTimeOut() {
return timeOut;
}
@override
set timeOut(int? _timeOut) {
timeOut = _timeOut;
}
}
so my question why i got error if i don't implement the setter even if the class has a constructor ?
In Dart, a non-final
field is implicitly equivalent to providing a getter and a setter with that field's name. A final
field is implicitly equivalent to providing a getter with no setter.
Therefore your base class provides an interface with getters and setters. But when you try to override it with a final
field in the derived class, you're no longer providing an implicit setter, and now your derived class would no longer implement the base class's required interface (and therefore the derived class would no longer substitutable where the base class is expected). That is not allowed, so you get a compile-time error.
If you don't want the derived class to provide a setter, don't make a setter part of the base class interface:
abstract class API {
int? get timeOut;
}
class GetData implements API {
@override
final int? timeOut;
GetData(int? ta) : timeOut = ta;
}
Note that the getTimeOut
method is redundant; you already have a timeOut
getter (and also see Why should I avoid wrapping fields in getters and setters?).