Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Dart Tutorial

Dart HOME Dart Intro Dart Get Started Dart Syntax Dart Output Dart Comments Dart Variables Dart final and const Dart Data Types Dart Numbers Dart Strings Dart String Interpolation Dart String Methods Dart Booleans Dart Type Conversion Dart Null Safety Dart late Dart Operators Dart Arithmetic Dart Assignment Dart Comparison Dart Logical Dart Type Test Dart Null Operators Dart Cascade Dart If...Else Dart Switch Dart While Loop Dart For Loop Dart Break/Continue

Dart Collections

Dart Lists Dart Access List Items Dart Change List Items Dart Loop Lists Dart List Methods Dart Sets Dart Maps Dart Access Map Items Dart Loop Maps Dart Collection if/for Dart Spread Operator

Dart Functions

Dart Functions Dart Parameters Dart Named Parameters Dart Return Values Dart Arrow Functions Dart Anonymous Functions Dart Closures Dart Scope Dart Recursion

Dart Classes

Dart OOP Dart Classes/Objects Dart Constructors Dart Named Constructors Dart Factory Constructors Dart Getters and Setters Dart Static Members Dart Inheritance Dart Abstract Classes Dart Interfaces Dart Mixins Dart Extension Methods Dart Enums Dart Generics

Dart 3 Features

Dart Records Dart Patterns Dart Switch Expressions Dart Sealed Classes Dart Class Modifiers

Dart Errors

Dart Exceptions Dart Custom Exceptions

Dart Async

Dart Async Intro Dart Futures Dart async/await Dart Streams Dart Isolates

Dart Libraries

Dart Imports Dart Packages Dart Math Dart Dates Dart JSON Dart RegExp Dart User Input Dart Files Dart Testing

Dart Examples

Dart Examples Dart Exercises


Dart Factory Constructors


Share

Dart Factory Constructors

A normal constructor always creates a new object of its own class.

A factory constructor is more flexible, and it is marked with the factory keyword.

It works like a function that must return an object, and it can decide which object to return.

A factory constructor can:

  • check or change the arguments before an object is created
  • return an object that already exists, instead of a new one
  • return an object of a subclass
  • create an object from data, like a Map

A Simple Factory

This factory constructor cleans up the name before it calls the normal constructor:

Example

class Person {
  final String name;

  Person._(this.name);

  factory Person(String name) {
    var clean = name.trim();
    if (clean.isEmpty) {
      clean = 'Unknown';
    }
    return Person._(clean);
  }
}

void main() {
  print(Person('  Liam  ').name);
  print(Person('').name);
}
Try it Yourself »

Result:

Liam
Unknown

Example Explained

  • Person._() is a named constructor called _.
  • A name that starts with an underscore _ is private, which means it can only be used in the same file.
  • The factory Person() has a body with normal code, and ends with return.
  • Outside of the file, the only way to create a Person is through the factory, so every name is always cleaned.

Note: A factory constructor cannot use this, because no object exists yet when it starts.

It cannot use the this.x shorthand or an initializer list either.



Return a Cached Object

A factory constructor can return an object that was created before.

This is called caching, and it saves memory when the same object is needed many times.

In this example, the class keeps all the colors it has created in a Map:

Example

class Color {
  final String name;

  static final Map<String, Color> _cache = {};

  Color._(this.name) {
    print('Creating $name');
  }

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

void main() {
  var a = Color('red');
  var b = Color('red');
  var c = Color('blue');

  print(identical(a, b));
  print(identical(a, c));
}
Try it Yourself »

Result:

Creating red
Creating blue
true
false

The keyword static means that there is only one _cache, shared by the whole class, and not one for each object.

You will learn more about it in the Static chapter.

The method putIfAbsent() returns the color that is already in the Map, or creates a new one and adds it.

"Creating red" is printed only once, because the second Color('red') returns the same object.


Return a Subtype

A factory constructor can return an object of a subclass.

A subclass is a class that is based on another class, and it is created with the extends keyword.

You will learn about subclasses in the Inheritance chapter.

Here, the factory Animal.fromSound() decides which kind of animal to create:

Example

class Animal {
  Animal();

  factory Animal.fromSound(String sound) {
    if (sound == 'woof') {
      return Dog();
    }
    if (sound == 'meow') {
      return Cat();
    }
    return Animal();
  }

  String describe() => 'An animal';
}

class Dog extends Animal {
  @override
  String describe() => 'A dog';
}

class Cat extends Animal {
  @override
  String describe() => 'A cat';
}

void main() {
  print(Animal.fromSound('woof').describe());
  print(Animal.fromSound('meow').describe());
  print(Animal.fromSound('moo').describe());
}
Try it Yourself »

Result:

A dog
A cat
An animal

The code that calls Animal.fromSound() does not need to know about Dog or Cat.

As you can see, a factory constructor can also be a named constructor.


Create an Object From a Map

The most common use of a factory constructor is to create an object from a Map.

Data from the internet often comes as JSON, a text format that Dart turns into a Map with string keys.

By convention, this factory is called fromJson:

Example

class User {
  final String name;
  final int age;

  User(this.name, this.age);

  factory User.fromJson(Map<String, dynamic> json) {
    return User(json['name'] as String, json['age'] as int);
  }

  @override
  String toString() => 'User($name, $age)';
}

void main() {
  var data = {'name': 'Emma', 'age': 28};

  var user = User.fromJson(data);
  print(user);
}
Try it Yourself »

Result:

User(Emma, 28)

The type dynamic means that the values in the Map can be of any type.

The as keyword tells Dart which type each value has.

A factory works well here, because it can read and check the Map before it creates the object.

You can use it with map() to turn a list of Maps into a list of objects:

Example

class User {
  final String name;
  final int age;

  User(this.name, this.age);

  factory User.fromJson(Map<String, dynamic> json) {
    return User(json['name'] as String, json['age'] as int);
  }

  @override
  String toString() => 'User($name, $age)';
}

void main() {
  var data = [
    {'name': 'Liam', 'age': 31},
    {'name': 'Olivia', 'age': 24},
  ];

  var users = data.map((item) => User.fromJson(item)).toList();
  print(users);
}
Try it Yourself »

Result:

[User(Liam, 31), User(Olivia, 24)]

You will learn how to read real JSON text in the JSON chapter.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.