Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
DART Cookbook

You're reading from   DART Cookbook Over 110 incredibly effective, useful, and hands-on recipes to design Dart web client and server applications

Arrow left icon
Product type Paperback
Published in Oct 2014
Publisher Packt
ISBN-13 9781783989621
Length 346 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Ivo Balbaert Ivo Balbaert
Author Profile Icon Ivo Balbaert
Ivo Balbaert
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Working with Dart Tools FREE CHAPTER 2. Structuring, Testing, and Deploying an Application 3. Working with Data Types 4. Object Orientation 5. Handling Web Applications 6. Working with Files and Streams 7. Working with Web Servers 8. Working with Futures, Tasks, and Isolates 9. Working with Databases 10. Polymer Dart Recipes 11. Working with Angular Dart 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...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image