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 Getters and Setters


Share

Dart Getters and Setters

A getter is a special method that reads a value.

A setter is a special method that changes a value.

From the outside, getters and setters look like normal fields.

You use them without parentheses ().

You create a getter with the get keyword:

Example

class Person {
  String firstName;
  String lastName;

  Person(this.firstName, this.lastName);

  String get fullName {
    return '$firstName $lastName';
  }
}

void main() {
  var person = Person('John', 'Doe');
  print(person.fullName);
}
Try it Yourself »

Result:

John Doe

Notice that we wrote person.fullName, not person.fullName().


Computed Properties

A getter does not store a value.

It computes the value every time you read it.

This is called a computed property.

A short getter is often written with the arrow syntax =>:

Example

class Rectangle {
  double width;
  double height;

  Rectangle(this.width, this.height);

  double get area => width * height;
}

void main() {
  var rect = Rectangle(4, 5);
  print(rect.area);

  rect.width = 10;
  print(rect.area);
}
Try it Yourself »

Result:

20.0
50.0

When the width changed, the area changed too, because it is computed again.



Private Fields

A name that starts with an underscore _ is private.

In Dart, private means private to the library.

A library is usually one .dart file.

Code in the same file can use a private name, but code in other files cannot.

A common pattern is a private field with a public getter.

Other files can read the value, but they cannot change it:

Example

class BankAccount {
  double _balance = 0;

  double get balance => _balance;

  void deposit(double amount) {
    _balance += amount;
  }
}

void main() {
  var account = BankAccount();
  account.deposit(100);
  account.deposit(50);
  print(account.balance);
}
Try it Yourself »

Result:

150.0

Note: Dart has no private or public keywords.

The underscore at the start of the name is the only thing that makes it private.

There is no setter for balance, so you get an error if you try to assign to it:

Example

class BankAccount {
  double _balance = 0;

  double get balance => _balance;
}

void main() {
  var account = BankAccount();
  account.balance = 1000;
}
Try it Yourself »

Result:

main.dart:9:11: Error: The setter 'balance' isn't defined for the type 'BankAccount'.
 - 'BankAccount' is from 'main.dart'.
Try correcting the name to the name of an existing setter, or defining a setter or field named 'balance'.
  account.balance = 1000;
          ^^^^^^^

Setters

You create a setter with the set keyword.

A setter has exactly one parameter: the new value.

You call it with the normal assignment operator =:

Example

class Temperature {
  double celsius = 0;

  double get fahrenheit => celsius * 9 / 5 + 32;

  set fahrenheit(double value) {
    celsius = (value - 32) * 5 / 9;
  }
}

void main() {
  var temp = Temperature();
  temp.fahrenheit = 212;
  print(temp.celsius);
  print(temp.fahrenheit);
}
Try it Yourself »

Result:

100.0
212.0

The getter and the setter have the same name, fahrenheit.


Check a Value in a Setter

A setter is a good place to check a value before you store it.

This is called validation.

In this example, the age is only changed if the new value is not negative:

Example

class Person {
  String name;
  int _age = 0;

  Person(this.name);

  int get age => _age;

  set age(int value) {
    if (value < 0) {
      print('Age cannot be negative');
    } else {
      _age = value;
    }
  }
}

void main() {
  var person = Person('Linus');
  person.age = 30;
  print(person.age);

  person.age = -5;
  print(person.age);
}
Try it Yourself »

Result:

30
Age cannot be negative
30

Tip: Only write getters and setters when they do something useful.

If a getter and a setter only read and write a field, a public field is simpler.



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.