Skip to content
Dart

Classes and Constructors

Define classes with named and factory constructors.

By EZ4Code Team
classconstructoroop

Code

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)
}

Explanation

Dart constructors: default (this. shorthand for field init), named (ClassName.x for variants), factory (returns instance, can be cached/subclass). Initializer list (: field = value) runs before body. Getters look like properties. @override marks method overrides (linter enforces). Use final for one-time assignment fields.

More Dart Snippets