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

Using a factory constructor


Dart gives us many flexible and succinct ways to build objects through constructors:

  • With optional arguments, such as in the Person constructor where salary is optional:

    class Person{
      String name;
      num salary
      Person(this.name, {this.salary});
    } 
  • With named constructors (a bonus for readable self-documenting code), for example, where a BankAccount for the same owner as acc is created:

    BankAccount.sameOwner(BankAccount acc): owner = acc.owner;
  • With const constructors, as shown in the following code:

    class ImmutableSquare {
    finalnum length;
    static finalImmutableSquare ONE = const ImmutableSquare(1);
    constImmutableSquare(this.length);
    }

However, modern modular software applications require more flexible ways to build and return objects, often extracted into a factory design pattern (for more information, refer to http://en.wikipedia.org/wiki/Factory_(object-oriented_programming)). Dart has this pattern built right into the language with factory constructors.

How to do...