Flutter中如何使用接口与基类

在Flutter开发中,如何正确使用接口(abstract class)与基类?我尝试定义一个抽象类作为接口,但实现时遇到类型转换问题。具体场景:多个组件需要共用相同方法签名但不同实现,用抽象类定义接口后,子类实现时出现"implements"和"extends"的使用混淆。请问:

  1. Dart中接口与基类的最佳实践是什么?
  2. 什么时候该用implements而不是extends?
  3. 如何避免在多层继承时出现方法冲突?
2 回复

在Flutter中,使用接口通过implements关键字实现多个接口,基类通过extends继承单继承。例如:

class BaseClass {}
class Interface1 {}
class Interface2 {}
class MyClass extends BaseClass implements Interface1, Interface2 {}

接口定义方法需全部实现,基类可复用父类逻辑。

更多关于Flutter中如何使用接口与基类的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在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:定义接口规范,可包含具体实现

选择依据:需要复用代码用继承,需要多态性用接口,两者都需要用抽象类。

回到顶部