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 Named Constructors


Share

Dart Named Constructors

A class can only have one constructor with the same name as the class.

If you try to write a second one, the program does not run:

Example

class Point {
  final int x;
  final int y;

  Point(this.x, this.y);

  Point() : x = 0, y = 0;
}

void main() {
  print(Point().x);
}
Try it Yourself »

Result:

main.dart:7:3: Error: 'Point' is already declared in this scope.
  Point() : x = 0, y = 0;
  ^^^^^
main.dart:5:3: Context: Previous declaration of 'Point'.
  Point(this.x, this.y);
  ^^^^^
main.dart:11:9: Error: Can't use 'Point' because it is declared more than once.
  print(Point().x);
        ^

But sometimes you want to create objects in different ways.

For this, Dart has named constructors.

A named constructor is written as the class name, a dot, and a name of your choice:

ClassName.constructorName(parameters)

Create a Named Constructor

This Point class has a normal constructor, and a named constructor called Point.origin(), which always creates the point (0, 0):

Example

class Point {
  final int x;
  final int y;

  Point(this.x, this.y);

  Point.origin()
      : x = 0,
        y = 0;
}

void main() {
  var p1 = Point(3, 4);
  var p2 = Point.origin();

  print('p1: ${p1.x}, ${p1.y}');
  print('p2: ${p2.x}, ${p2.y}');
}
Try it Yourself »

Result:

p1: 3, 4
p2: 0, 0

You call a named constructor with the class name, a dot, and the constructor name.

The named constructor uses an initializer list to set the fields.



More Than One Named Constructor

A class can have as many named constructors as you need.

Good names make the code easy to read, because they tell you how the object is created:

Example

class Temperature {
  final double celsius;

  Temperature(this.celsius);

  Temperature.fromFahrenheit(double fahrenheit)
      : celsius = (fahrenheit - 32) * 5 / 9;

  Temperature.freezing() : celsius = 0;
}

void main() {
  var t1 = Temperature(25);
  var t2 = Temperature.fromFahrenheit(212);
  var t3 = Temperature.freezing();

  print(t1.celsius);
  print(t2.celsius);
  print(t3.celsius);
}
Try it Yourself »

Result:

25.0
100.0
0.0

A named constructor can also use the this.x shorthand and have a body:

Example

class Player {
  final String name;
  final int level;

  Player(this.name, this.level);

  Player.beginner(this.name) : level = 1 {
    print('Welcome, $name!');
  }
}

void main() {
  var player = Player.beginner('Emma');
  print('${player.name} starts at level ${player.level}');
}
Try it Yourself »

Result:

Welcome, Emma!
Emma starts at level 1

Redirecting Constructors

Often, a named constructor does almost the same work as another constructor.

Instead of repeating the code, it can call the other constructor.

This is called a redirecting constructor.

You write a colon, then this(...) with the arguments for the main constructor:

Example

class Car {
  final String brand;
  final int year;

  Car(this.brand, this.year);

  Car.newModel(String brand) : this(brand, 2026);
}

void main() {
  var car1 = Car('Ford', 1969);
  var car2 = Car.newModel('Volvo');

  print('${car1.brand} ${car1.year}');
  print('${car2.brand} ${car2.year}');
}
Try it Yourself »

Result:

Ford 1969
Volvo 2026

Car.newModel('Volvo') sends 'Volvo' and 2026 to the main constructor Car(), which creates the object.

A redirecting constructor can also call another named constructor, with this. and the name of that constructor:

Example

class Point {
  final int x;
  final int y;

  Point.xy(this.x, this.y);

  Point.onXAxis(int x) : this.xy(x, 0);
}

void main() {
  var p = Point.onXAxis(7);
  print('${p.x}, ${p.y}');
}
Try it Yourself »

Result:

7, 0

Note: A redirecting constructor cannot have a body, and it cannot set fields itself.

All the work is done by the constructor it redirects to.



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.