Question #75EasyDart Basics

What is Object Oriented Programming in Dart: Classes & Objects ?

#dart

Answer

Overview

Classes are blueprints for creating objects. Objects are instances of classes. Classes bundle data (fields/properties) and behavior (methods) together.


Class Definition

dart
class Person {
  // Fields (properties)
  String name;
  int age;
  String? email; // Nullable

  // Constructor
  Person(this.name, this.age, {this.email});

  // Named constructor
  Person.anonymous() : name = 'Anonymous', age = 0;

  // Instance method
  void greet() => print('Hi, I am $name, age $age');

  // Getter (computed property)
  bool get isAdult => age >= 18;

  // Method with return
  String introduce() => 'My name is $name. I am $age years old.';

  // Static method (class-level)
  static Person create(Map<String, dynamic> data) {
    return Person(data['name'], data['age']);
  }

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

Creating Objects (Instances)

dart
void main() {
  // Create objects (instances of Person)
  final alice = Person('Alice', 28, email: 'alice@example.com');
  final bob = Person('Bob', 17);
  final anon = Person.anonymous();

  // Access fields
  print(alice.name);    // Alice
  print(bob.isAdult);   // false
  alice.greet();        // Hi, I am Alice, age 28

  // Static method — called on class, not instance
  final carol = Person.create({'name': 'Carol', 'age': 30});
  print(carol); // Person(name: Carol, age: 30)
}

Class Features in Dart

dart
class Product {
  // Final fields — set once
  final int id;

  // Late — initialized later
  late String _cachedDescription;

  String name;
  double price;
  static int _totalProducts = 0; // Static field — shared across all instances

  Product(this.id, this.name, this.price) {
    _totalProducts++; // Runs on every instantiation
  }

  // Static getter
  static int get totalProducts => _totalProducts;

  // Computed getter
  String get priceLabel => '₹${price.toStringAsFixed(2)}';

  // Operator overloading
  bool operator ==(Object other) =>
      other is Product && id == other.id;

  
  int get hashCode => id.hashCode;
}

Class Relationships

dart
// Inheritance (is-a)
class AdminUser extends User { ... }

// Interface (can-do)
class Dog implements Trainable { ... }

// Mixin (has-behavior)
class FlutterDev with CodeStyle, Debuggable { ... }

// Composition (has-a) — preferred
class Order {
  final User user;       // Has a User
  final List<Product> items; // Has Products
}

Key Concept: Everything in Flutter is a class —

text
Widget
,
text
Text
,
text
Column
,
text
StatelessWidget
are all classes. When you write
text
Text('Hello')
, you're calling the
text
Text
class constructor and creating an object.