Dart Setter Method
Dart Setter method
In this tutorial, we will learn about the Dart Setter method, which sets or initializes the values of the fields. We can declare the setter method using the set keyword with one parameter.
Syntax
The general syntax for the setter method is as follows:
void set setter_name(data_type param) {
this.field_name = param;
}
Example
/* Setter and Getter Demo Program Dart Tutorials - www.TestingDocs.com */ class Book { late String title; late String author; late double price; // setter methods void set book_title(String title) { this.title = title; } void set book_author(String author) { this.author = author; } void set book_price(double p) { this.price = p; } // getter methods String get book_author { return author; } String get book_title { return title; } double get book_price { return price; } } void main() { // create book object Book bObj = new Book(); bObj.book_author = "Sears & Zemansky"; bObj.book_title = "University Physics"; bObj.book_price = 99.99; // print book object print("Book Author: " + bObj.book_author); print("Book Title : " + bObj.book_title); print("Book Price :\$ " + bObj.book_price.toString()); }
Program Output
Book Author: Sears & Zemansky
Book Title : University Physics
Book Price :$ 99.99
In this example, we have used setter methods to set the book object properties and getter methods to retrieve the book object values.
—
Dart Tutorials
Dart tutorial on this website can be found at:
https://www.testingdocs.com/dart-tutorials-for-beginners/
More information on Dart: