Junior
How to declare an interface in Dart?
sobes.tech AI
Answer from AI
In Dart, there is no explicit keyword interface. Interfaces are implicitly declared by defining a class. Any class in Dart can serve as an interface.
A class implementing an interface must declare the keyword implements before the class name and list the names of the interfaces it implements.
// Interface is implicitly defined by this class.
class MyInterface {
void doSomething() {}
int getData() {
return 0;
}
}
// Class implementing the interface.
class Implementer implements MyInterface {
@override
void doSomething() {
// Implementation of the interface method
print('Doing something...');
}
@override
int getData() {
// Implementation of the interface method
return 42;
}
}
void main() {
MyInterface obj = Implementer();
obj.doSomething();
print(obj.getData());
}
If a class implements multiple interfaces, they can be listed separated by commas:
class AnotherInterface {
String getName() {
return '';
}
}
class MultiImplementer implements MyInterface, AnotherInterface {
@override
void doSomething() {
print('Doing something from MyInterface...');
}
@override
int getData() {
return 100;
}
@override
String getName() {
return 'Multirealizer';
}
}
Using an abstract class also allows defining an interface, but with the possibility of containing non-abstract methods and instance variables. However, for a pure contract definition, a regular class or even an abstract class with all abstract methods is often used.