---
title: "Encapsulating Data with Getters and Setters in Dart"
date: "2026-12-03T10:08:00+07:00"
description: "Every property access in Dart is really a getter or setter call. Learn to declare computed properties, validate writes, and hide fields behind them."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/dart-getters-setters.jpg"
alt: "Conceptual illustration of a public property interface shielding a private data field inside a class"
tags: ['dart', 'dart-language', 'oop', 'encapsulation', 'getters-setters']
---

In Dart, a plain field access and a method call are the same kind of thing — which means you can expose a clean, property-shaped API while the implementation does whatever work it likes underneath.

## Every property access is a function call

Every property access — top-level, static, or instance — is an invocation of a getter or a setter. A variable implicitly creates a getter and, if it is mutable, a setter, so reading and writing a bare field already calls small functions in the background:

```dart
class Point {
  double x = 0;
}

void main() {
  final p = Point();
  p.x = 5; // invokes the implicit setter
  print(p.x); // invokes the implicit getter, prints 5.0
}
```

Because fields are just "particularly fast getters", Dart lets you swap a stored field for a computed one without touching a single call site. That indirection is the whole point: the client asks for a value without needing to know whether it is stored or calculated, which gives the provider the freedom to change how the property works.

## Declaring computed properties

Use the `get` and `set` keywords to declare properties whose values are computed on access. A classic example derives a value that was never stored anywhere:

```dart
class Spacecraft {
  String name;
  DateTime? launchDate;
  Spacecraft(this.name, this.launchDate);
  int? get launchYear => launchDate?.year;
}

void main() {
  final voyager = Spacecraft('Voyager 1', DateTime.utc(1977, 9, 5));
  print(voyager.launchYear); // 1977
}
```

`launchYear` stores nothing. Every read recomputes it from `launchDate`, so there is no cached copy that can drift out of sync — Effective Dart's **AVOID storing what you can calculate** guidance makes the same point about `area` and `circumference` on a circle. Compute first; cache only when a performance problem proves you must.

## Validating writes in setters

A setter is the natural gatekeeper for incoming values, and callers still see a plain property write:

```dart
class Volume {
  double _level = 0;
  double get level => _level;
  set level(double newValue) {
    if (newValue < 0 || newValue > 100) {
      throw RangeError.range(newValue, 0, 100, 'level');
    }
    _level = newValue;
  }
}

void main() {
  final volume = Volume();
  volume.level = 42;
  print(volume.level); // 42.0
}
```

Assignment reads like a field write at the call site while the class keeps its invariant on the way in. This is exactly the "field-like" shape Effective Dart asks for: a setter takes a single argument, produces no result value, changes some state, and is idempotent — setting `level` to `42` twice behaves exactly like setting it once.

## Hide the field, expose the property

Dart's privacy is library-level: a leading underscore makes a member private to its library. The standard encapsulation pattern pairs a private field with a public getter and setter that add behavior on the way through:

```dart
String _secret = 'Hello';
String get secret => _secret.toUpperCase();
set secret(String newMessage) {
  if (newMessage.isNotEmpty) _secret = newMessage;
}

void main() {
  print(secret); // HELLO
  secret = 'Dart is fun';
  print(secret); // DART IS FUN
}
```

Callers see one clean property. Internally you are free to uppercase on read and reject empty writes — or to stop storing the value at all — without breaking anyone. For fields that need this treatment inside a class, the same shape applies: a private `_level` with a public `level` property.

## When *not* to write a getter and setter

Encapsulation does not mean wrapping every field in boilerplate. Three rules keep the noise down:

```dart
class Box {
  Object? contents; // Good: just expose the field.
}

class Basket {
  final items = <String>[]; // Good: read-only via `final`.
}

// Bad: pointless forwarding pair (unnecessary_getters_setters).
class Crate {
  Object? _contents;
  Object? get contents => _contents;
  set contents(Object? value) => _contents = value;
}
```

Dart fields and getters/setters are completely indistinguishable to callers, so you can expose a field today and wrap it later without touching call sites — the Java habit of pre-wrapping everything buys nothing here. For a read-only property, **PREFER using a `final` field** over the private-field-plus-getter dance, and don't reach for that pattern until you actually need to mutate internally. One more asymmetry to avoid: **DON'T define a setter without a corresponding getter** (`avoid_setters_without_getters`), because a write-only "dropbox" property confuses users who expect `=` and `+=` to behave consistently. If a piece of state can be modified but should not be exposed the same way, make it a method instead — `folder.rename('new')` reads better than a setter nobody can read back.

## Top-level getters and setters

Getters and setters are not class-only. You can declare them at the top level of a library, exactly like variables with extra behavior: `String get greeting => _greeting.toUpperCase();` alongside `set greeting(String value) => _greeting = value.toLowerCase();` gives a library a property that behaves like a real one. Everything in this post — implicit properties, validation, privacy, and the lints — applies equally to top-level, static, and instance properties, which is why the language docs describe every property access the same way regardless of where it lives.

## Choosing between a getter and a method

A getter signals "field-like": the caller cares about the result, not how it was produced. Use this checklist to decide:

| Question | Getter | Method |
| --- | --- | --- |
| Does it take arguments? | No | Yes, usually |
| Is it idempotent? | Yes | Not required |
| Does it have user-visible side effects? | No | Often the point |
| What should the name be? | Noun or non-imperative verb | Imperative verb |
| Example | `rectangle.area` | `database.downloadData()` |

The design guidelines behind the table are **DO use getters for operations that conceptually access properties** and **DO use setters for operations that conceptually change properties** (`use_setters_to_change_properties`). If the work itself matters to the caller — network I/O, an exponential calculation — draw attention to it with a verb-named method instead: `connection.nextIncomingMessage` would be a lie if it quietly hit the network. Naming follows the same logic: **AVOID starting a function or method name with `get`** — replace `getBreakfastOrder()` with a getter named `breakfastOrder`, or pick a real verb like `fetch` or `calculate`. A boolean property should read as a predicate (`isEmpty`, `canClose`, `isEnabled`), never as a command.

## Takeaways

- Every dotted property access in Dart is a getter or setter invocation, so fields and computed properties are interchangeable to callers.
- Getters let you derive values instead of caching them; setters let you validate and normalize writes behind a plain `=` call site.
- Prefer a `final` field for read-only state, and never ship a setter without a getter or a getter that just forwards to a field.
- Use getters when the operation is argument-free, side-effect-free, and idempotent; use imperative-named methods when the work is the point.
- **Takeaway:** encapsulation in Dart is a property-shaped facade — keep fields private or final, and let getters and setters decide what the world can see.

## References

- https://dart.dev/language/functions
- https://dart.dev/effective-dart/design
- https://dart.dev/effective-dart/usage
