Interface Classes
Interface Classes
About
- Interface classes define pure contracts.
- Support multiple implementation.
- Enforce API compliance.
- Promote loose coupling.
Main Topics
-
Explicit Interfaces
- Definition:
interface
modifier. - Example:
interface class DataStore { Future<Data> fetch(); }
- Definition:
-
Implementation
- Definition:
implements
keyword. - Example:
class SqlStore implements DataStore { @override Future<Data> fetch() {...} }
- Definition:
-
Multiple Interfaces
- Definition: Composing contracts.
- Example:
class FileCache implements Reader, Writer {...}
-
API Design
- Definition: Stable public contracts.
- Example:
interface class PaymentGateway { Future<Receipt> charge(Amount amount); }
How to Use
- Declare: Use
interface
modifier - Implement: Use
implements
keyword - Compose: Multiple interfaces per class
- Document: Clear contract definitions
How It Works
- Enforcement: Must implement all members
- Decoupling: Consumers depend on interfaces
- Testing: Easy mocking of interfaces
Example Session:
void main() {
DataStore store = SqlStore(); // Interface reference
await store.fetch();
}
Conclusion
Interface classes enable robust system design through explicit contracts, facilitating testing, modularity, and future-proof API evolution in Dart codebases.