Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Dart Getter and Setter

In Dart, getters and setters are used to control access to the properties of a class. They allow you to execute custom code when getting or setting the value of a property. Here's how you can define getters and setters in Dart:


Getter

1. Getters are methods that are used to retrieve the value of a property.
2. In Dart, getters do not require parentheses when they are accessed.
3. They are defined using the get keyword followed by the getter name.
4. Getters are typically used to provide read-only access to properties.

class MyClass {
int _value = 0; // Private variable
// Getter for accessing the value
int get value => _value;
} void main() {
var obj = MyClass();
print(obj.value); // Accessing the getter
}


Setters

1. Setters are methods that are used to set the value of a property.
2. They are defined using the set keyword followed by the setter name.
3. Setters are typically used to provide write-only or validation logic when setting the value of properties.

class MyClass {
int _value = 0; // Private variable
// Getter for accessing the value
int get value => _value;
// Setter for setting the value
set value(int newValue) {
if (newValue >= 0) {
_value = newValue;
} else {
throw ArgumentError('Value must be non-negative.');
}
}
}
void main() {
var obj = MyClass();
obj.value = 10; // Setting the value using the setter
print(obj.value); // Accessing the value using the getter
}

Getters and setters allow you to encapsulate the internal representation of a class and provide controlled access to its properties, enabling better data integrity and encapsulation.






Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java