Skip to content
Dart

Classes and Constructors

Define classes with named and factory constructors.

#class#constructor#oop

Code

dart
class Person {
  String name;
  int age;

  // Main constructor with this. shorthand
  Person(this.name, this.age);

  // Named constructor
  Person.born(String name) : this(name, 0);

  // Named with initializer list
  Person.fromJson(Map<String, dynamic> json)
      : name = json['name'] as String,
        age = json['age'] as int;

  // Factory (can return subclass or cached)
  factory Person.anonymous() => Person('Anon', 0);

  // Method
  String greet() => 'Hi, I am $name ($age)';

  // Getter
  bool get isAdult => age >= 18;

  @override
  String toString() => 'Person($name, $age)';
}

void main() {
  final p = Person('Alice', 30);
  print(p.greet());           // Hi, I am Alice (30)
  print(p.isAdult);           // true

  final baby = Person.born('Bob');
  print(baby.age);            // 0

  final fromJson = Person.fromJson({'name': 'Carol', 'age': 25});
  print(fromJson);            // Person(Carol, 25)
}