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 Classes and Objects


Share

Dart Classes

A class is a blueprint for objects.

To create a class, use the class keyword, followed by the name of the class and curly brackets:

class Car {
  String brand = 'Ford';
  int year = 1969;
}

The variables inside a class are called fields, or properties.

The class Car has two fields: brand and year.

Note: Class names start with an uppercase letter, like Car or ShoppingCart.


Create an Object

To create an object, write the name of the class followed by parentheses ().

Then use a dot . to read the fields of the object:

Example

class Car {
  String brand = 'Ford';
  int year = 1969;
}

void main() {
  var myCar = Car();
  print(myCar.brand);
  print(myCar.year);
}
Try it Yourself »

Result:

Ford
1969

Note: In some other languages, you must write new Car() to create an object.

In Dart, the new keyword is optional, and modern Dart code leaves it out.

Change Fields

You can also change the value of a field with the dot syntax.

Each object has its own copy of the fields, so changing one object does not change the others:

Example

class Car {
  String brand = 'Ford';
  int year = 1969;
}

void main() {
  var car1 = Car();
  var car2 = Car();

  car2.brand = 'Volvo';
  car2.year = 2020;

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

Result:

Ford 1969
Volvo 2020


Methods

A function that belongs to a class is called a method.

Methods describe what an object can do, and they can use the fields of the object:

Example

class Car {
  String brand = 'Ford';
  int speed = 0;

  void accelerate(int amount) {
    speed += amount;
    print('$brand is now driving $speed km/h');
  }
}

void main() {
  var myCar = Car();
  myCar.accelerate(30);
  myCar.accelerate(20);
}
Try it Yourself »

Result:

Ford is now driving 30 km/h
Ford is now driving 50 km/h

You call a method with the object name, a dot, and the method name with parentheses.


The this Keyword

The keyword this means "the current object", which is the object that the method was called on.

You need it when a parameter has the same name as a field.

In the method below, brand alone means the parameter, and this.brand means the field:

Example

class Car {
  String brand = 'Ford';
  int year = 1969;

  void update(String brand, int year) {
    this.brand = brand;
    this.year = year;
  }
}

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

Result:

Toyota 2015

When no parameter or local variable has the same name, you can leave this out, like in the accelerate() method above.


A First Constructor

In the examples above, every new car starts as a Ford from 1969.

A constructor is a special function that runs when an object is created, and it lets you give each object its own values.

The constructor has the same name as the class.

The short form Car(this.brand, this.year); puts the arguments directly into the fields:

Example

class Car {
  String brand;
  int year;

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

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

Result:

Volvo 2020
Toyota 2015

Now the fields do not need a starting value, because the constructor always gives them one.

You will learn much more about this in the Constructors chapter.


The toString() Method

If you print an object, Dart does not know which fields to show.

It only prints a general text with the name of the class:

Example

class Car {
  String brand;
  int year;

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

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

Result:

Instance of 'Car'

Every class has a method called toString(), which print() uses to turn an object into text.

You can write your own version of it in your class, with @override on the line above:

Example

class Car {
  String brand;
  int year;

  Car(this.brand, this.year);

  @override
  String toString() => 'Car($brand, $year)';
}

void main() {
  var myCar = Car('Volvo', 2020);
  print(myCar);
  print('My car: $myCar');
}
Try it Yourself »

Result:

Car(Volvo, 2020)
My car: Car(Volvo, 2020)

@override tells Dart that you replace a method that the class already has.

String interpolation also uses toString(), so '$myCar' gives the same text.



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.