flutter
/

Dart Classes and Objects – Complete Beginner to Advanced Guide

Last Sync: Today

On this page

12
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

flutter

Dart Classes and Objects – Complete Beginner to Advanced Guide

What is a Class in Dart?

A class is a blueprint used to create objects. It defines properties (variables) and behaviors (methods). In Dart, everything is treated as an object, making classes a core concept of the language.

Basic Class Example

A class is defined using the class keyword. It contains fields (data) and methods (functions).

DARTRead-only
1
class Person {
  String name = '';
  int age = 0;

  void sayHello() {
    print('Hello, my name is $name');
  }
}

Creating Objects (Instances)

Objects are created using constructors. The new keyword is optional in Dart.

DARTRead-only
1
void main() {
  var person = Person();
  person.name = 'Alice';
  person.age = 30;
  person.sayHello();
}

Constructors in Dart

Constructors initialize objects. If not defined, Dart automatically provides a default constructor.

Parameterized Constructor

DARTRead-only
1
class Person {
  String name;
  int age;

  Person(this.name, this.age);

  void introduce() {
    print('I am $name and I am $age years old');
  }
}

Named Constructors

Named constructors allow multiple ways to create objects.

DARTRead-only
1
class Person {
  String name;
  int age;

  Person(this.name, this.age);

  Person.guest() {
    name = 'Guest';
    age = 18;
  }

  Person.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        age = json['age'];
}

Using the this Keyword

this refers to the current instance of the class and is used to avoid naming conflicts.

DARTRead-only
1
class Point {
  int x, y;

  Point(int x, int y) {
    this.x = x;
    this.y = y;
  }
}

Getters and Setters (Important Fix)

Use private variables with getters and setters to control access and validation.

DARTRead-only
1
class Rectangle {
  double _width;
  double height;

  Rectangle(this._width, this.height);

  double get area => _width * height;

  set width(double value) {
    if (value > 0) {
      _width = value;
    } else {
      throw ArgumentError('Width must be positive');
    }
  }
}

Static Members

DARTRead-only
1
class MathUtils {
  static const double pi = 3.14159;

  static int add(int a, int b) => a + b;
}

Encapsulation in Dart

Dart uses library-level privacy. Variables starting with _ are private to the file.

DARTRead-only
1
class BankAccount {
  String _accountNumber;
  double _balance = 0;

  BankAccount(this._accountNumber);

  void deposit(double amount) {
    if (amount > 0) _balance += amount;
  }

  double get balance => _balance;
}

Complete Real-World Example

DARTRead-only
1
class Student {
  String name;
  int age;
  final int id;
  static int _nextId = 1000;

  Student(this.name, this.age) : id = _nextId++;

  Student.anonymous()
      : name = 'Anonymous',
        age = 0,
        id = _nextId++;

  void introduce() {
    print('Student #$id: $name, $age years old');
  }

  String get description => 'ID $id: $name ($age)';
}

Best Practices

    • Always use constructor shorthand when possible
    • Use _ for private fields
    • Prefer final for immutable data
    • Use named constructors for clarity
    • Avoid heavy logic inside constructors
    • Keep classes small and focused

Try it yourself

class Car {
  String brand;
  int year;

  Car(this.brand, this.year);

  void describe() {
    print('$brand car from $year');
  }
}

void main() {
  var car = Car('Toyota', 2023);
  car.describe();
}

Test Your Knowledge

Q1
of 4

Which keyword is used to define a class in Dart?

A
class
B
object
C
struct
D
define
Q2
of 4

What does `this` refer to in Dart?

A
Parent class
B
Current instance
C
Static context
D
Constructor only
Q3
of 4

What is the purpose of a constructor?

A
Delete objects
B
Initialize objects
C
Print values
D
Run loops
Q4
of 4

What will be the output? class A { static int count = 0; A() { count++; } } void main() { A(); A(); print(A.count); }

A
0
B
1
C
2
D
Error

Frequently Asked Questions

Can a class be private in Dart?

Dart doesn't have private keywords. Instead, library‑level privacy is achieved by prefixing an identifier with _. If you want a class to be private to a file, place it in its own file and don't export it.

What is the difference between a class and an object?

A class is a blueprint (definition), while an object is an instance created from that blueprint. For example, Person is a class; var alice = Person('Alice', 30) creates an object alice.

Can a class extend multiple classes?

No, Dart supports single inheritance – a class can extend only one superclass. However, you can implement multiple interfaces and use mixins to reuse code from multiple sources.

What is the purpose of a constructor?

A constructor initializes a new instance of a class. It sets initial values for fields and performs any setup required before the object is used.

How do you make a variable read‑only from outside the class?

Declare it as final (if set once) or make it private (_var) and provide only a getter (no setter).

Previous

dart collection if for

Next

dart constructors

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.