Skip to content

Commit 5ed8190

Browse files
conooiparlough
andauthored
add section for getters and setters (#6830)
Added a section for getters and setters. Fixes #5477 Preview: https://dart-dev--pr6830-getters-setters-bcxd3yuk.web.app/language/functions#getters-and-setters --- - [x] I’ve reviewed the contributor guide and applied the relevant portions to this PR. - [x] This PR doesn't contain automatically generated corrections or text (Grammarly, LLMs, and similar). - [x] This PR follows the [Google Developer Documentation Style Guidelines](https://developers.google.com/style) — for example, it doesn't use _i.e._ or _e.g._, and it avoids _I_ and _we_ (first person). - [x] This PR uses [semantic line breaks](https://github.com/dart-lang/site-shared/blob/main/doc/writing-for-dart-and-flutter-websites.md#semantic-line-breaks) of 80 characters or fewer. <details> <summary>Contribution guidelines:</summary><br> - See our [contributor guide](https://github.com/dart-lang/site-www/blob/main/CONTRIBUTING.md) for general expectations for PRs. - Larger or significant changes should be discussed in an issue before creating a PR. - Code changes should generally follow the [Dart style guide](https://dart.dev/effective-dart) and use `dart format`. - Updates to [code excerpts](https://github.com/dart-lang/site-shared/blob/main/packages/excerpter) indicated by `<?code-excerpt` need to be updated in their source `.dart` file as well. </details> --------- Co-authored-by: Parker Lougheed <[email protected]>
1 parent 660c71d commit 5ed8190

File tree

3 files changed

+137
-16
lines changed

3 files changed

+137
-16
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Defines a variable `_secret` that is private to the library since
2+
// its identifier starts with an underscore (`_`).
3+
String _secret = 'Hello';
4+
5+
// A public top-level getter that
6+
// provides read access to [_secret].
7+
String get secret {
8+
print('Getter was used!');
9+
return _secret.toUpperCase();
10+
}
11+
12+
// A public top-level setter that
13+
// provides write access to [_secret].
14+
set secret(String newMessage) {
15+
print('Setter was used!');
16+
if (newMessage.isNotEmpty) {
17+
_secret = newMessage;
18+
print('New secret: "$newMessage"');
19+
}
20+
}
21+
22+
void main() {
23+
// Reading the value calls the getter.
24+
print('Current message: $secret');
25+
26+
/*
27+
Output:
28+
Getter was used!
29+
Current message: HELLO
30+
*/
31+
32+
// Assigning a value calls the setter.
33+
secret = 'Dart is fun';
34+
35+
// Reading it again calls the getter to show the new computed value
36+
print('New message: $secret');
37+
38+
/*
39+
Output:
40+
Setter was used! New secret: "Dart is fun"
41+
Getter was used!
42+
New message: DART IS FUN
43+
*/
44+
}

pubspec.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ workspace:
99
- examples
1010
- site
1111
- tool/dash_site
12+

src/content/language/functions.md

Lines changed: 92 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: Functions
33
description: Everything about functions in Dart.
4-
js: [{url: '/assets/js/inject_dartpad.js', defer: true}]
4+
js: [{ url: "/assets/js/inject_dartpad.js", defer: true }]
55
prevpage:
66
url: /language/error-handling
77
title: Error handling
@@ -62,8 +62,8 @@ that indicates whether the `atomicNumber` falls into the noble gas range.
6262

6363
## Parameters
6464

65-
A function can have any number of *required positional* parameters. These can be
66-
followed either by *named* parameters or by *optional positional* parameters
65+
A function can have any number of _required positional_ parameters. These can be
66+
followed either by _named_ parameters or by _optional positional_ parameters
6767
(but not both).
6868

6969
:::note
@@ -75,7 +75,6 @@ details.
7575
You can use [trailing commas][] when you pass arguments to a function
7676
or when you define function parameters.
7777

78-
7978
### Named parameters
8079

8180
Named parameters are optional
@@ -97,9 +96,9 @@ void enableFlags({bool? bold, bool? hidden}) {
9796
}
9897
```
9998

100-
When calling a function,
99+
When calling a function,
101100
you can specify named arguments using
102-
<code><em>paramName</em>: <em>value</em></code>.
101+
<code><em>paramName</em>: <em>value</em></code>.
103102
For example:
104103

105104
<?code-excerpt "misc/lib/language_tour/functions.dart (use-named-parameters)"?>
@@ -144,6 +143,7 @@ A parameter marked as `required` can still be nullable:
144143
```dart
145144
const Scrollbar({super.key, required [!Widget?!] child});
146145
```
146+
147147
:::
148148

149149
You might want to place positional arguments first,
@@ -274,7 +274,7 @@ More about those in the next section.
274274

275275
## Function types
276276

277-
You can specify the type of a function, which is known as a *function type*.
277+
You can specify the type of a function, which is known as a _function type_.
278278
A function type is obtained from a function declaration header by
279279
replacing the function name by the keyword `Function`.
280280
Moreover, you are allowed to omit the names of positional parameters, but
@@ -309,8 +309,8 @@ These functions are called _anonymous functions_, _lambdas_, or _closures_.
309309

310310
An anonymous function resembles a named function as it has:
311311

312-
* Zero or more parameters, comma-separated
313-
* Optional type annotations between parentheses.
312+
- Zero or more parameters, comma-separated
313+
- Optional type annotations between parentheses.
314314

315315
The following code block contains the function's body:
316316

@@ -511,7 +511,6 @@ void main() {
511511
}
512512
```
513513

514-
515514
## Return values
516515

517516
All functions return a value. If no return value is specified, the
@@ -534,14 +533,92 @@ To return multiple values in a function, aggregate the values in a [record][].
534533

535534
[record]: /language/records#multiple-returns
536535

536+
## Getters and setters
537+
538+
Every property access (top-level, static, or instance) is an invocation
539+
of a getter or a setter. A variable implicitly creates a getter
540+
and, if it's mutable, a setter. This is why when you access a property,
541+
you're actually calling a small function in the background. Reading a
542+
property calls a getter function, and writing one calls a setter function,
543+
even in cases where the property is declared a variable.
544+
545+
However, you can also declare getters and setters explicitly with
546+
the `get` and `set` keywords respectively.
547+
This allows a property's value to be computed when it's read or written.
548+
549+
The purpose of using getters and setters is to create a clear
550+
separation between the client (the code that uses the property) and
551+
the provider (the class or library that defines it). The client asks for or
552+
sets a value without needing to know if that value is stored in a
553+
simple variable or calculated on the spot. This gives the provider
554+
the freedom to change how the property works.
555+
556+
For example, because the value of the property might not be stored anywhere,
557+
it could be computed each time the getter is called. Another example
558+
is that when a value is stored in a private variable, and public access
559+
is only allowed by calling a getter or a setter.
560+
561+
The following example showcases this,
562+
with the `secret` getter and setter providing
563+
indirect access to the private variable `_secret` with
564+
its own manipulations on the assigned and retrieved values.
565+
566+
<?code-excerpt "language/lib/functions/getters_setters.dart"?>
567+
```dart highlightLines=3,7-10,14-20,24,33
568+
// Defines a variable `_secret` that is private to the library since
569+
// its identifier starts with an underscore (`_`).
570+
String _secret = 'Hello';
571+
572+
// A public top-level getter that
573+
// provides read access to [_secret].
574+
String get secret {
575+
print('Getter was used!');
576+
return _secret.toUpperCase();
577+
}
578+
579+
// A public top-level setter that
580+
// provides write access to [_secret].
581+
set secret(String newMessage) {
582+
print('Setter was used!');
583+
if (newMessage.isNotEmpty) {
584+
_secret = newMessage;
585+
print('New secret: "$newMessage"');
586+
}
587+
}
588+
589+
void main() {
590+
// Reading the value calls the getter.
591+
print('Current message: $secret');
592+
593+
/*
594+
Output:
595+
Getter was used!
596+
Current message: HELLO
597+
*/
598+
599+
// Assigning a value calls the setter.
600+
secret = 'Dart is fun';
601+
602+
// Reading it again calls the getter to show the new computed value
603+
print('New message: $secret');
604+
605+
/*
606+
Output:
607+
Setter was used! New secret: "Dart is fun"
608+
Getter was used!
609+
New message: DART IS FUN
610+
*/
611+
}
612+
```
613+
537614
## Generators
538615

539616
When you need to lazily produce a sequence of values,
540617
consider using a _generator function_.
541618
Dart has built-in support for two kinds of generator functions:
542619

543-
* **Synchronous** generator: Returns an [`Iterable`] object.
544-
* **Asynchronous** generator: Returns a [`Stream`] object.
620+
- **Synchronous** generator: Returns an [`Iterable`] object.
621+
- **Asynchronous** generator: Returns a [`Stream`] object.
545622

546623
To implement a **synchronous** generator function,
547624
mark the function body as `sync*`,
@@ -580,7 +657,6 @@ Iterable<int> naturalsDownFrom(int n) sync* {
580657
}
581658
```
582659

583-
584660
[`Iterable`]: {{site.dart-api}}/dart-core/Iterable-class.html
585661
[`Stream`]: {{site.dart-api}}/dart-async/Stream-class.html
586662

@@ -601,22 +677,22 @@ heavily platform specific, so check out the interop docs on, for example,
601677
[C][] or [JavaScript][] to learn more.
602678

603679
External functions can be top-level functions, [instance methods][],
604-
[getters or setters][], or [non-redirecting constructors][].
680+
getters or setters, or [non-redirecting constructors][].
605681
An [instance variable][] can be `external` too,
606682
which is equivalent to an external getter and (if the variable
607683
is not `final`) an external setter.
608684

609685
[instance methods]: /language/methods#instance-methods
610-
[getters or setters]: /language/methods#getters-and-setters
611686
[non-redirecting constructors]: /language/constructors#redirecting-constructors
612687
[instance variable]: /language/classes#instance-variables
613688
[C]: /interop/c-interop
614689
[JavaScript]: /interop/js-interop
615-
616690
[Function API reference]: {{site.dart-api}}/dart-core/Function-class.html
617691
[Callable objects]: /language/callable-objects
618692
[type annotations for public APIs]: /effective-dart/design#do-type-annotate-fields-and-top-level-variables-if-the-type-isnt-obvious
619693
[if statement]: /language/branches#if
620694
[conditional expression]: /language/operators#conditional-expressions
621695
[Flutter]: {{site.flutter}}
622696
[trailing commas]: /language/collections#lists
697+
698+

0 commit comments

Comments
 (0)