Skybinary

View Categories

Understand Classes and Objects in Dart

2 min read

1. Understand Classes and Objects in Dart #

Understanding classes and objects is the foundation of Object-Oriented Programming in Dart. A class acts as a template, while objects are the actual instances created from that template. Mastering this step will help you structure your Dart applications in an organized and scalable way.

Define and Instantiate Classes #

A class represents a blueprint that describes the properties and behavior of an object. It contains variables (called properties) and functions (called methods).

Example:

class Person {
  String name;
  int age;

  void displayInfo() {
    print("Name: $name, Age: $age");
  }
}

Once a class is defined, you can create objects (instances) from it.

void main() {
  Person p1 = Person();
  p1.name = "Shoaib";
  p1.age = 24;
  p1.displayInfo();
}

Use Constructors and Named Constructors #

A constructor is a special method used to initialize an object when it is created.

Default Constructor Example:

class Person {
  String name;
  int age;

  Person(this.name, this.age);
}

Using the constructor:

var person = Person("Ali", 30);

Dart also supports named constructors, which allow multiple ways to create an object.

class Student {
  String name;
  int rollNo;

  Student(this.name, this.rollNo);

  Student.fromJson(Map data) {
    name = data['name'];
    rollNo = data['rollNo'];
  }
}

Using a named constructor:

var student = Student.fromJson({"name": "Aqib", "rollNo": 12});

Access and Modify Object Properties #

You can access or update class properties using dot notation.

var person = Person("Shoaib", 24);
print(person.name);      // Accessing property
person.age = 25;         // Modifying property

Dart also supports getters and setters to control and validate property access.

class BankAccount {
  double _balance = 0;

  double get balance => _balance;

  set balance(double amount) {
    if (amount >= 0) {
      _balance = amount;
    }
  }
}

Apply Methods for Behavior #

Methods define the actions an object can perform.

class Car {
  String model;
  int speed = 0;

  Car(this.model);

  void accelerate() {
    speed += 10;
  }

  void showSpeed() {
    print("Current speed: $speed");
  }
}

Using methods:

void main() {
  var car = Car("Civic");
  car.accelerate();
  car.showSpeed();
}

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top