In Dart, an abstract class is a class that cannot be instantiated directly; it serves as a blueprint for other classes. Abstract classes are used to define common properties and methods that subclasses must implement, ensuring a consistent interface across different implementations. You can include both abstract methods (methods without a body) and regular methods (with implementation) in an abstract class.
For example:
abstract class Vehicle {
void start(); // abstract method
void stop() {
print('Vehicle stopped'); // concrete method
}
}
class Car extends Vehicle {
@override
void start() {
print('Car started');
}
}
void main() {
// var v = Vehicle(); // Error: cannot instantiate abstract class
var myCar = Car();
myCar.start();
myCar.stop(); // inherited concrete method
}
Here, Vehicle defines an abstract method start() that Car must implement, while also providing a concrete method stop() that can be used as-is.
I’ve applied abstract classes in Flutter projects when creating a base model or service class. For instance, I created an abstract ApiService class with abstract methods like fetchData() and postData(), and then implemented these methods in different subclasses for specific APIs. This ensured all API services followed the same interface.
A challenge I faced was understanding when to use an abstract class versus an interface (implemented via implements). The limitation is that abstract classes support single inheritance, so for combining multiple contracts, using mixins or interfaces becomes necessary.
