Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Dart notes · Topic 10 of 19 · 6 min read

Dart classes and objects

Dart classes notes with examples: fields, methods, constructors, named and const constructors, private members with _, getters, setters, static and toString.

Classes and objects

A class is a blueprint; an object is one thing made from it. The class Student describes what every student has (a name, marks) and can do (show a report). Asha and Rohit are two objects, or instances, of that class.

  • Fields hold an object's data.
  • Methods are functions that belong to the class.
class Student {
  String name;
  int marks;

  Student(this.name, this.marks);

  bool get passed => marks >= 33;

  void report() {
    print('$name: $marks (${passed ? 'Pass' : 'Fail'})');
  }
}

void main() {
  var asha = Student('Asha', 88);
  var rohit = Student('Rohit', 29);
  asha.report();
  rohit.report();
  rohit.marks += 10;
  rohit.report();
}
Asha: 88 (Pass)
Rohit: 29 (Fail)
Rohit: 39 (Pass)

In Dart you create objects by calling the constructor; the keyword new is optional and is normally left out.

Constructors

A constructor sets up a new object. Student(this.name, this.marks); is shorthand: each this.field parameter is copied straight into that field.

The long form does the same work:

class Point {
  int x;
  int y;
  Point(int x, int y)
      : x = x,
        y = y;
}

void main() {
  var p = Point(3, 4);
  print('${p.x}, ${p.y}');
}
3, 4

this refers to the current object. Constructors can have optional and named parameters exactly like functions:

class Product {
  final String name;
  final double price;
  final int qty;

  Product({required this.name, required this.price, this.qty = 1});

  double get total => price * qty;
}

void main() {
  var p = Product(name: 'Notebook', price: 45, qty: 4);
  print('${p.name}: ${p.total}');
}
Notebook: 180.0

Named constructors

A class can have several constructors with names, written ClassName.name:

class Temperature {
  final double celsius;
  Temperature(this.celsius);
  Temperature.fromFahrenheit(double f) : celsius = (f - 32) * 5 / 9;
  Temperature.freezing() : celsius = 0;
}

void main() {
  print(Temperature(37).celsius);
  print(Temperature.fromFahrenheit(212).celsius);
  print(Temperature.freezing().celsius);
}
37.0
100.0
0.0

fromJson constructors, used to turn server data into objects, are named constructors too.

Private members with _

In Dart a name that starts with an underscore, such as _balance, is private to its file (its library). Code in other files cannot see it. Expose what others need through methods and getters:

class BankAccount {
  final String owner;
  double _balance = 0;

  BankAccount(this.owner);

  double get balance => _balance;

  void deposit(double amount) {
    if (amount <= 0) {
      print('Invalid amount');
      return;
    }
    _balance += amount;
  }

  set limit(double value) => print('Limit set to $value');
}

void main() {
  var acc = BankAccount('Meena');
  acc.deposit(5000);
  acc.deposit(-20);
  print(acc.balance);
  acc.limit = 20000;
}
Invalid amount
5000.0
Limit set to 20000.0
  • A getter (get balance) looks like a field to the caller but runs code.
  • A setter (set limit) runs code when a value is assigned.
  • Because balance has no setter, acc.balance = 1; is an error: only deposit can change it.

static members

A static field or method belongs to the class itself, not to any one object. Call it on the class name.

class School {
  static const String name = 'BrainBit Infotech Academy';
  static int count = 0;
  final String student;

  School(this.student) {
    count++;
  }

  @override
  String toString() => '$student @ $name';
}

void main() {
  var a = School('Asha');
  var b = School('Rohit');
  print(a);
  print(School.count);
  print(b);
}
Asha @ BrainBit Infotech Academy
2
Rohit @ BrainBit Infotech Academy

toString is called whenever an object is printed or put inside a string. Overriding it (with @override) makes print(object) show something useful instead of Instance of 'School'.

const constructors

If every field is final, a class can have a const constructor. const objects with the same values are created once and shared, which is why Flutter asks you to write const in front of widgets that never change.

class Colour {
  final int r, g, b;
  const Colour(this.r, this.g, this.b);
}

void main() {
  const red1 = Colour(255, 0, 0);
  const red2 = Colour(255, 0, 0);
  print(identical(red1, red2));
}
true

Lists of objects

class Book {
  final String title;
  final double price;
  Book(this.title, this.price);
}

void main() {
  var books = [Book('Dart Basics', 350), Book('Flutter Apps', 499), Book('DSA', 299)];
  books.sort((a, b) => a.price.compareTo(b.price));
  for (var b in books) {
    print('${b.title.padRight(14)} Rs ${b.price}');
  }
  var total = books.fold<double>(0, (sum, b) => sum + b.price);
  print('Total: Rs $total');
}
DSA            Rs 299.0
Dart Basics    Rs 350.0
Flutter Apps   Rs 499.0
Total: Rs 1148.0

Common mistakes

  • A non-nullable field with no value: *Field 'name' should be initialized because its type 'String' doesn't allow null.* Set it in the constructor, give a default, or make it late or nullable.
  • Calling an instance method on the class (Student.report()) or a static one on an object.
  • Expecting _name to be private to the class: it is private to the file.
  • Forgetting @override on toString, so a typo such as tostring silently adds a new method.
  • Writing const before a constructor of a class that has non-final fields.

Key points

  • A class bundles fields (data) and methods (behaviour); objects are instances of it.
  • ClassName(this.a, this.b) copies parameters into fields; named constructors add more ways to build.
  • _name makes a member private to its file; getters and setters control access.
  • static members belong to the class.
  • Override toString for readable output; use const constructors for unchanging objects.

Practice questions

1. Write a class Rectangle with width and height, a getter area and a method isSquare().
class Rectangle {
  final double width, height;
  Rectangle(this.width, this.height);
  double get area => width * height;
  bool isSquare() => width == height;
}

void main() {
  var r = Rectangle(4, 4);
  print(r.area);         // 16.0
  print(r.isSquare());   // true
}
2. What does print(obj) show for a class that does not override toString?

Instance of 'ClassName', for example Instance of 'Student'.

3. Add a named constructor Student.guest() that creates a student called 'Guest' with 0 marks.
class Student {
  final String name;
  final int marks;
  Student(this.name, this.marks);
  Student.guest() : name = 'Guest', marks = 0;
}

void main() {
  var g = Student.guest();
  print('${g.name} ${g.marks}');   // Guest 0
}
4. How do you make a field private in Dart, and private to what?

Start its name with an underscore, such as _balance. It is then private to the file (library) it is declared in.

5. Write a class Counter with a static field that counts how many Counter objects have been made.
class Counter {
  static int made = 0;
  Counter() {
    made++;
  }
}

void main() {
  Counter();
  Counter();
  Counter();
  print(Counter.made);   // 3
}