Search⌘ K
AI Features

Advanced Class Mechanics

Explore advanced Dart class mechanics to customize object string output, manage static members, control instance creation with factory constructors, enforce method contracts using implicit interfaces, and reuse code through mixins. This lesson deepens your understanding of Dart's object-oriented programming features for cleaner, scalable code.

Customizing string representations

When we print an object in Dart, the default output is often unhelpful, displaying something like Instance of 'Person'. This happens because our class inherits a basic toString() method from the root Object class.

To provide a readable description of our object, we can override the toString() method and define a custom text format.

Dart
class Person {
String name;
int age;
Person(this.name, this.age);
@override
String toString() {
return 'Person(name: $name, age: $age)';
}
}
void main() {
final person = Person('Sarah', 25);
print(person);
}
  • Line 7: We apply the @override annotation to modify the inherited string behavior.

  • Lines 8—10: We return a formatted string that includes the actual state of our instance variables.

  • Line 15: We pass the object directly to the print function. Dart automatically calls our overridden method, outputting our custom string instead of the generic default.

Static members

Properties and methods normally belong to individual ...