Dart Objects

Creating and working with object instances

🎯 What are Dart Objects?

Objects are instances of classes in Dart. They represent real-world entities with properties and behaviors. Each object has its own memory space and can perform actions.


// Creating objects from a class
class Phone {
  String brand = 'iPhone';
  void call() => print('Calling...');
}

Phone myPhone = Phone(); // Creating an object
myPhone.call(); // Using the object
                                    

Object Characteristics

🏷️

Identity

Each object has a unique identity

Car car1 = Car();
Car car2 = Car();
print(car1 == car2); // false
📦

State

Objects store data in properties

Person person = Person();
person.name = 'Alice';
person.age = 25;

Behavior

Objects can perform actions

Dog dog = Dog();
dog.bark();
dog.run();
dog.sleep();
🔗

Interaction

Objects can communicate

Teacher teacher = Teacher();
Student student = Student();
teacher.teach(student);

🔹 Creating Objects

There are several ways to create objects in Dart:

class Book {
  String title;
  String author;
  int pages;
  
  // Constructor
  Book(this.title, this.author, this.pages);
  
  void read() {
    print('Reading "$title" by $author');
  }
  
  void getInfo() {
    print('Title: $title');
    print('Author: $author');
    print('Pages: $pages');
  }
}

void main() {
  // Method 1: Using constructor
  Book book1 = Book('1984', 'George Orwell', 328);
  
  // Method 2: Using new keyword (optional)
  Book book2 = new Book('To Kill a Mockingbird', 'Harper Lee', 376);
  
  // Method 3: Type inference
  var book3 = Book('The Great Gatsby', 'F. Scott Fitzgerald', 180);
  
  // Using the objects
  book1.getInfo();
  book1.read();
  
  print('---');
  
  book2.getInfo();
  book2.read();
}

Output:

Title: 1984

Author: George Orwell

Pages: 328

Reading "1984" by George Orwell

---

Title: To Kill a Mockingbird

Author: Harper Lee

Pages: 376

Reading "To Kill a Mockingbird" by Harper Lee

🔹 Object Properties and Methods

Access and modify object properties and call methods:

class Smartphone {
  String brand;
  String model;
  double batteryLevel;
  bool isOn;
  
  Smartphone(this.brand, this.model) {
    batteryLevel = 100.0;
    isOn = false;
  }
  
  void turnOn() {
    if (!isOn) {
      isOn = true;
      print('$brand $model is now ON');
    } else {
      print('Phone is already ON');
    }
  }
  
  void turnOff() {
    if (isOn) {
      isOn = false;
      print('$brand $model is now OFF');
    } else {
      print('Phone is already OFF');
    }
  }
  
  void useBattery(double amount) {
    if (batteryLevel > amount) {
      batteryLevel -= amount;
      print('Battery: ${batteryLevel.toStringAsFixed(1)}%');
    } else {
      print('Low battery! Please charge.');
    }
  }
}

void main() {
  // Create smartphone object
  Smartphone myPhone = Smartphone('Apple', 'iPhone 14');
  
  // Access properties
  print('Brand: ${myPhone.brand}');
  print('Model: ${myPhone.model}');
  print('Battery: ${myPhone.batteryLevel}%');
  
  // Call methods
  myPhone.turnOn();
  myPhone.useBattery(25.5);
  myPhone.useBattery(30.0);
  myPhone.turnOff();
}

Output:

Brand: Apple

Model: iPhone 14

Battery: 100.0%

Apple iPhone 14 is now ON

Battery: 74.5%

Battery: 44.5%

Apple iPhone 14 is now OFF

🔹 Multiple Objects

Create and manage multiple objects from the same class:

class Student {
  String name;
  int rollNumber;
  List marks = [];
  
  Student(this.name, this.rollNumber);
  
  void addMark(int mark) {
    marks.add(mark);
    print('$name: Added mark $mark');
  }
  
  double getAverage() {
    if (marks.isEmpty) return 0.0;
    int total = marks.reduce((a, b) => a + b);
    return total / marks.length;
  }
  
  void displayReport() {
    print('--- Student Report ---');
    print('Name: $name');
    print('Roll Number: $rollNumber');
    print('Marks: ${marks.join(', ')}');
    print('Average: ${getAverage().toStringAsFixed(2)}');
    print('');
  }
}

void main() {
  // Create multiple student objects
  List students = [
    Student('Alice', 101),
    Student('Bob', 102),
    Student('Charlie', 103),
  ];
  
  // Add marks for each student
  students[0].addMark(85);
  students[0].addMark(92);
  students[0].addMark(78);
  
  students[1].addMark(76);
  students[1].addMark(88);
  students[1].addMark(91);
  
  students[2].addMark(95);
  students[2].addMark(89);
  students[2].addMark(93);
  
  // Display reports for all students
  for (Student student in students) {
    student.displayReport();
  }
}

Output:

Alice: Added mark 85

Alice: Added mark 92

Alice: Added mark 78

Bob: Added mark 76

Bob: Added mark 88

Bob: Added mark 91

Charlie: Added mark 95

Charlie: Added mark 89

Charlie: Added mark 93

--- Student Report ---

Name: Alice

Roll Number: 101

Marks: 85, 92, 78

Average: 85.00

🧠 Test Your Knowledge

How do you create an object from a class in Dart?