Skybinary

View Categories

1. Understand Classes and Objects in Dart

1 min read

Understanding Classes and Objects in Dart #

Classes and objects are the foundation of Object-Oriented Programming (OOP). They help developers model real-world entities in code by combining data and behavior into a single unit. In Dart, every application relies heavily on classes and objects, especially when building Flutter applications.


What Is a Class? #

A class is a blueprint or template used to create objects. It defines the properties (variables) and behaviors (methods) that the objects created from it will have. A class itself does not occupy memory until an object is created from it.

In Dart, a class is declared using the class keyword.

Example:

class Car {
  String brand;
  int year;

  Car(this.brand, this.year);

  void displayInfo() {
    print('Brand: $brand, Year: $year');
  }
}

In this example:

  • Car is a class.
  • brand and year are properties.
  • displayInfo() is a method that defines the behavior of the class.

What Is an Object? #

An object is an instance of a class. When an object is created, memory is allocated and the class blueprint is used to initialize its properties and methods.

Example:

void main() {
  Car myCar = Car('Toyota', 2022);
  myCar.displayInfo();
}

Here:

  • myCar is an object of the Car class.
  • The object holds actual values for brand and year.
  • The method displayInfo() is called using the object.

Relationship Between Class and Object #

  • A class defines what an object will look like and how it will behave.
  • An object represents a real entity created from that class.
  • Multiple objects can be created from a single class, each with different data.

Example:

void main() {
  Car car1 = Car('Honda', 2021);
  Car car2 = Car('BMW', 2023);

  car1.displayInfo();
  car2.displayInfo();
}

Each object maintains its own state while sharing the same structure and behavior.


Constructors in Classes #

A constructor is a special method used to initialize objects. Dart provides a simple and concise constructor syntax.

Example:

class Student {
  String name;
  int rollNo;

  Student(this.name, this.rollNo);
}

When an object is created, the constructor automatically assigns values to the properties.


Why Classes and Objects Are Important #

  • They help organize code into logical units.
  • They promote reusability and scalability.
  • They make large applications easier to maintain.
  • They are the core building blocks of Flutter widgets and application architecture.

Real-World Usage in Flutter #

In Flutter:

  • Each widget is a class.
  • Screens, buttons, services, and models are all implemented using classes.
  • Objects are created to manage UI state, API responses, and business logic.

Powered by BetterDocs

Leave a Reply

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

Scroll to Top