在Flutter中,接口和基类用于实现代码复用和多态性。以下是具体使用方法:
1. 基类(继承)
使用extends关键字实现继承:
class Animal {
void eat() {
print('Animal is eating');
}
}
class Dog extends Animal {
@override
void eat() {
print('Dog is eating dog food');
}
void bark() {
print('Woof!');
}
}
// 使用
Dog dog = Dog();
dog.eat(); // 输出: Dog is eating dog food
dog.bark(); // 输出: Woof!
2. 接口(隐式接口)
Dart中每个类都隐式定义了一个接口:
class AnimalInterface {
void eat();
void sleep();
}
class Cat implements AnimalInterface {
@override
void eat() {
print('Cat is eating fish');
}
@override
void sleep() {
print('Cat is sleeping');
}
}
// 使用
AnimalInterface cat = Cat();
cat.eat(); // 输出: Cat is eating fish
3. 抽象类
结合接口和基类的特性:
abstract class Animal {
void eat(); // 抽象方法
void sleep() { // 具体方法
print('Animal is sleeping');
}
}
class Bird extends Animal {
@override
void eat() {
print('Bird is eating seeds');
}
}
4. 实际应用示例
abstract class ApiService {
Future<dynamic> fetchData(String url);
}
class HttpApiService implements ApiService {
@override
Future<dynamic> fetchData(String url) async {
// 实现HTTP请求逻辑
final response = await http.get(Uri.parse(url));
return response.body;
}
}
// 在Flutter中使用
class MyWidget extends StatelessWidget {
final ApiService apiService;
MyWidget({required this.apiService});
@override
Widget build(BuildContext context) {
// 使用apiService
return Container();
}
}
关键区别:
extends:继承实现,获得父类功能
implements:实现接口,必须重写所有方法
abstract:定义接口规范,可包含具体实现
选择依据:需要复用代码用继承,需要多态性用接口,两者都需要用抽象类。