Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 73 ยท Dart essentials

Classes, Constructors and Mixins

Learn Dart classes for Flutter: constructors, named, factory and const constructors, inheritance, abstract classes, mixins, extension methods and enums with fields.

Everything you build in Flutter is a class: every widget, every State, every model. Dart's classes have a few features you will not find in other languages, such as shorthand constructors, const constructors and mixins. Learning them now makes widget code much less mysterious, because a widget is just a class whose constructor takes named parameters.

Dart code in this lesson is read-only. The JavaScript TryIts are stand-ins that imitate the same ideas (JavaScript has classes and a different mixin style), so you can see the behavior.

A first class

DART
class Player {
  final String name;
  int score;

  Player(this.name, this.score);

  void addPoints(int points) {
    score += points;
  }

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

void main() {
  final p = Player('Ada', 10);
  p.addPoints(5);
  print(p);             // Ada: 15
}

Player(this.name, this.score) is a generating constructor with initializing formals: it declares the parameters and assigns them to the fields in one line. No new keyword is needed to create an object.

There is no public or private. A name that starts with an underscore (_secret) is private to its library (usually its file).

Constructor flavors

Five kinds of constructor

Generative The normal one. Sets up fields.
Named Extra entry points like Player.guest().
Factory May return a cached or different object.
const Builds a compile-time constant object.

Flutter widgets use const and named parameters on almost every class.

1 / 2

Named parameters in constructors

Flutter widgets take named parameters, written with braces:

DART
class Player {
  final String name;
  final int score;

  const Player({required this.name, this.score = 0});
}

final a = Player(name: 'Ada');             // score 0
final b = Player(name: 'Grace', score: 7);

Named constructors

A class can have several constructors with names:

DART
class Player {
  final String name;
  final int score;

  Player(this.name, this.score);

  Player.guest()
      : name = 'Guest',
        score = 0;

  Player.fromMap(Map<String, Object?> map)
      : name = map['name'] as String,
        score = map['score'] as int;
}

final p = Player.fromMap({'name': 'Ada', 'score': 9});

The part after the colon is the initializer list. It assigns final fields before the constructor body runs. fromMap constructors are the standard way to turn JSON into objects (see HTTP Requests and JSON).

Factory constructors

A factory constructor does not have to create a new object. It can return an existing one or a subtype:

DART
class Logger {
  static final Map<String, Logger> _cache = {};
  final String name;

  Logger._(this.name);

  factory Logger(String name) {
    return _cache.putIfAbsent(name, () => Logger._(name));
  }
}

print(identical(Logger('app'), Logger('app')));   // true: same object

Logger._ is a private named constructor; the public factory controls who may create instances.

const constructors

If all fields are final, the constructor can be const. Two const objects with equal values are the same object in memory:

DART
class Point {
  final int x, y;
  const Point(this.x, this.y);
}

const a = Point(1, 2);
const b = Point(1, 2);
print(identical(a, b));   // true

This is why const Text('Hi') is cheap in Flutter: the framework can skip rebuilding a widget that is identical to the previous one.

Inheritance and abstract classes

Use extends to inherit and super to call the parent:

DART
abstract class Shape {
  double area();                 // no body: subclasses must implement

  String describe() => 'Area: ${area().toStringAsFixed(1)}';
}

class Circle extends Shape {
  final double radius;
  Circle(this.radius);

  @override
  double area() => 3.14159 * radius * radius;
}

class Square extends Shape {
  final double side;
  Square(this.side);

  @override
  double area() => side * side;
}

An abstract class cannot be instantiated. StatelessWidget and StatefulWidget are abstract classes that require you to implement build or createState. Every override is marked with @override, which lets the analyzer catch typos.

Every class also acts as an interface. implements promises the same members without inheriting any code:

DART
class Fake implements Shape {
  @override
  double area() => 1;
  @override
  String describe() => 'fake';
}

Mixins

Dart has single inheritance, so a class can have only one parent. A mixin is a bundle of fields and methods that you can add to any class with with, without making it a parent:

DART
mixin Swimmer {
  void swim() => print('$this swims');
}

mixin Flyer {
  void fly() => print('$this flies');
}

class Animal {}

class Duck extends Animal with Swimmer, Flyer {
  @override
  String toString() => 'Duck';
}

Duck().swim();
Duck().fly();

You can limit who may use a mixin with on: mixin Logs on Animal can only be added to subclasses of Animal. Flutter uses mixins in several places; for instance SingleTickerProviderStateMixin gives a State class what animations need (you will use it in Explicit Animations and AnimationController).

JavaScript has no with, but you can copy methods onto a class. This TryIt shows the idea, so you can feel what "adding behavior without inheriting" means:

JS Mixins, imitated with Object.assign

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Extension methods

An extension adds methods to an existing type without touching its code:

DART
extension StringTools on String {
  String get firstUpper =>
      isEmpty ? this : this[0].toUpperCase() + substring(1);

  bool get isEmail => contains('@') && contains('.');
}

print('flutter'.firstUpper);        // Flutter
print('[email protected]'.isEmail);           // true

Flutter apps often add extensions on BuildContext (for context.theme) or on num (for 16.px style spacing). The extension is only visible where you import it.

Enums with fields

Dart enums can carry data and methods:

DART
enum Status {
  idle('Waiting', false),
  loading('Please wait', true),
  failed('Something broke', false);

  final String label;
  final bool showSpinner;

  const Status(this.label, this.showSpinner);

  bool get isBusy => this == Status.loading;
}

print(Status.loading.label);          // Please wait
print(Status.values.length);          // 3

Enums plus a switch expression are an ideal way to model UI states, since the compiler warns you if you forget a case.

Try it: a factory and a const-like cache

The same cache idea behind factory and const can be shown in JavaScript. A function returns the same object for equal inputs, and an identity check proves it:

JS Same input, same object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In Flutter, const widgets work the same way: the framework can notice "this is the same object as last time" and skip work.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a factory constructor allow that a normal constructor does not?

    A factory constructor must return an object but not necessarily a new one, so it can return cached instances.
  2. 2. What is a mixin used for?

    Dart has single inheritance. Mixins let a class reuse code from several sources.
  3. 3. When are two const objects with equal fields the same object?

    Dart canonicalizes compile-time constants, so identical const expressions share one instance. Flutter exploits this for const widgets.
  4. 4. How do you make a member private in Dart?

    A leading underscore makes a name library-private, usually meaning private to the file.

Summary

  • Constructors can use this.field shorthand, named parameters, named constructors, factory and const.
  • Use extends for one parent, implements for an interface and with for mixins.
  • Abstract classes define members that subclasses must implement.
  • Extensions add methods to existing types; enums can hold fields and methods.
  • A leading underscore means library-private.
  • All Dart is read-only here; the TryIts are JavaScript stand-ins.

Next: Collections and Generics