class Shape {
String color;
void draw() {
print('Draw Random Shape');
}
}
class Rectangle implements Shape {
@override
void draw() {
print('Draw Rectangle');
}
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是我收到一条警告说
缺少 getter Shape.color 和 setter Shape.color 的具体实现
我知道 dart 中的每个实例变量都有自己的 getter 和 setter。
Dart 不从 继承实现implements Shape
,而只声明Rectangle
符合 的接口Shape
。
您需要添加String color;
到Rectangle
以满足implements Shape
.
您可以通过添加一个字段或一个 getter 和一个 setter 来做到这一点。从类的接口角度来看,两者都是等价的。
class Rectangle implements Shape {
String color;
@override
void draw() {
print('Draw Rectangle');
}
}
Run Code Online (Sandbox Code Playgroud)
或者
class Rectangle implements Shape {
String _color;
String get color => _color;
set color(String value) => _color = value;
@override
void draw() {
print('Draw Rectangle');
}
}
Run Code Online (Sandbox Code Playgroud)
如果 getter 和 setter 只转发到没有附加代码的私有字段,则后者被认为是不好的风格。