Interfaces in Dart provide a powerful way to define contracts that classes must adhere to. They play a crucial role in creating consistent and maintainable code structures.
In Dart, interfaces are implicit. Any class can be used as an interface. This approach offers flexibility and simplicity in defining contracts for classes.
To implement an interface, use the implements
keyword. A class can implement multiple interfaces, separating them with commas.
class Animal {
void makeSound();
}
class Dog implements Animal {
@override
void makeSound() {
print('Woof!');
}
}
Interfaces can be combined with Dart Generics to create more flexible and reusable code structures.
abstract class Repository<T> {
Future<T> fetch(int id);
Future<void> save(T item);
}
class UserRepository implements Repository<User> {
@override
Future<User> fetch(int id) async {
// Implementation
}
@override
Future<void> save(User item) async {
// Implementation
}
}
While interfaces define a contract, Dart Abstract Classes can provide both a contract and a partial implementation. Choose based on your specific needs:
Interfaces | Abstract Classes |
---|---|
Define contract only | Can define contract and implementation |
Multiple interfaces can be implemented | Single inheritance only |
No constructor | Can have constructors |
Dart interfaces offer a flexible and powerful way to define contracts for classes. By leveraging interfaces, you can create more modular, maintainable, and scalable code. Remember to use them in conjunction with other Dart features like abstract classes and generics for maximum benefit.