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 Constructors


Share

Dart Constructors

A constructor is a special function that creates an object from a class.

It has the same name as the class, and it has no return type.

The most common kind is called a generative constructor, because it generates a new object every time it is called.

Here is a constructor with a body, which sets the fields and prints a message:

Example

class Car {
  String brand = '';
  int year = 0;

  Car(String brand, int year) {
    this.brand = brand;
    this.year = year;
    print('A new $brand was created');
  }
}

void main() {
  var myCar = Car('Volvo', 2020);
  print(myCar.year);
}
Try it Yourself »

Result:

A new Volvo was created
2020

This works, but the fields need a starting value ('' and 0), because they must have a value before the body of the constructor runs.


The this.x Shorthand

Setting fields from parameters is so common that Dart has a short form for it.

When you write this.brand as a parameter, the argument goes directly into the field brand:

Example

class Car {
  String brand;
  int year;

  Car(this.brand, this.year);
}

void main() {
  var myCar = Car('Volvo', 2020);
  print('${myCar.brand} ${myCar.year}');
}
Try it Yourself »

Result:

Volvo 2020

The constructor has no body, so it ends with a semicolon.

The fields do not need a starting value, because they get their value before the object is ready.

This also works with final fields, which cannot be changed after the object is created:

Example

class Person {
  final String name;
  final int age;

  Person(this.name, this.age);
}

void main() {
  var person = Person('Emma', 30);
  print('${person.name} is ${person.age} years old');
}
Try it Yourself »

Result:

Emma is 30 years old

Tip: Make fields final when they should not change.

It makes your classes safer and easier to understand.



Initializer List

Sometimes a field gets a value that is calculated from the parameters.

For this, you can use an initializer list.

It comes after a colon :, before the body of the constructor, and the parts are separated by commas:

Example

class Rectangle {
  final double width;
  final double height;
  final double area;

  Rectangle(this.width, this.height) : area = width * height;
}

void main() {
  var room = Rectangle(4, 5);
  print('Area: ${room.area}');
}
Try it Yourself »

Result:

Area: 20.0

The initializer list runs before the body, so it can set final fields.

The initializer list can set more than one field, and it can use parameters that are not fields:

Example

class User {
  final String name;
  final String email;

  User(String name, String email)
      : name = name.trim(),
        email = email.toLowerCase();
}

void main() {
  var user = User('  Olivia ', 'Olivia@Example.com');
  print('[${user.name}]');
  print(user.email);
}
Try it Yourself »

Result:

[Olivia]
olivia@example.com

In name = name.trim(), the left name is the field, and the right name is the parameter.


Named Parameters in Constructors

Constructors can have named parameters, just like functions.

Use required for the values that must always be given, and a default value for the others:

Example

class Pizza {
  final String name;
  final String size;
  final bool extraCheese;

  Pizza({required this.name, this.size = 'medium', this.extraCheese = false});
}

void main() {
  var p1 = Pizza(name: 'Margherita');
  var p2 = Pizza(name: 'Pepperoni', size: 'large', extraCheese: true);

  print('${p1.name}, ${p1.size}, ${p1.extraCheese}');
  print('${p2.name}, ${p2.size}, ${p2.extraCheese}');
}
Try it Yourself »

Result:

Margherita, medium, false
Pepperoni, large, true

Named arguments make it easy to see what each value means, and you can write them in any order.

If you forget a required argument, the program does not run:

Example

class Pizza {
  final String name;
  final String size;

  Pizza({required this.name, this.size = 'medium'});
}

void main() {
  var pizza = Pizza(size: 'small');
  print(pizza.name);
}
Try it Yourself »

Result:

main.dart:9:20: Error: Required named parameter 'name' must be provided.
  var pizza = Pizza(size: 'small');
                   ^
main.dart:5:3: Context: Found this candidate, but the arguments don't match.
  Pizza({required this.name, this.size = 'medium'});
  ^^^^^

Const Constructors

If all the fields of a class are final, you can mark the constructor with const.

Then you can create objects that are compile-time constants, which means their values are known before the program runs.

Dart creates each constant object only once, and reuses it when you create the same constant again:

Example

class Point {
  final int x;
  final int y;

  const Point(this.x, this.y);
}

void main() {
  const a = Point(1, 2);
  const b = Point(1, 2);
  var c = Point(1, 2);

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

Result:

true
false

The function identical() returns true when two variables point to the very same object.

a and b are the same object, but c is a new object, because it was not created with const.



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.