Book Image

DART Cookbook

By : Ivo Balbaert
Book Image

DART Cookbook

By: Ivo Balbaert

Overview of this book

Table of Contents (18 chapters)
Dart Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
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...