Book Image

DART Cookbook

By : Ivo Balbaert
Book Image

DART Cookbook

By: Ivo Balbaert

Overview of this book

If you are a Dart developer looking to sharpen your skills, and get insight and tips on how to put that knowledge into practice, then this book is for you. You should also have a basic knowledge of HTML, and how web applications with browser clients and servers work, in order to build dynamic Dart applications.
Table of Contents (13 chapters)
12
Index

Building a singleton


In some cases, you only need one unique instance of a class because this is simply enough for the app you're working with, or perhaps to save resources. This recipe shows you how to do this in Dart.

How to do it...

The singleton example shows how to do this (substitute your singleton class name for Immortal). Use a factory constructor to implement the singleton pattern, as shown in the following code:

class Immortal {
  static final Immortal theOne = new Immortal._internal('Connor MacLeod');
  String name;
  factory Immortal(name) => theOne;
  // private, named constructor
  Immortal._internal(this.name); }

main() {
  var im1 = new Immortal('Juan Ramirez');
  var im2 = new Immortal('The Kurgan');
  print(im1.name);               // Connor MacLeod
  print(im2.name);               // Connor MacLeod
  print(Immortal.theOne.name);   // Connor MacLeod
  assert(identical(im1, im2));
}

All Immortal instances are the same object.

How it works...

The Immortal class contains an...