{

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example


Setters and Getter allow you to read and update the data of a class object. It uses to achieve encapsulation

Dart setter and getter examples

In classes, Getters provide an access to read instance member variables. Setters allow you to update the instance variables of a class.

Getters are called accessors, Setters are known as Mutators.

In Dart, Getter and Setters are implicitly defined for every member declared in a class Still, You can customize the fields to write setters and getters

Getter’s syntax:

datatype get member_name{
// code to return members
}

Setters Syntax:

set  member_name{
// code to update members
}

Here is an example code

  • First, Declare fields or member variables in a class with type
  • provide setter and Getter methods with set and get keyword
  • Can access getter using an instance of a class assign the value to class field instance.field=value.
  • Getter can be accessed using instance.field.

Here is an example program

class Employee {
  int _eid;
  String _name;

  int get id {
    return _eid;
  }

  set id(int eid) {
    _eid = eid;
  }

  String get name {
    return _name;
  }

  set name(String name) {
    _name = name;
  }
}

void main() {
  Employee emp = Employee();
  emp.id = 12;
  emp.name = "john";

  print("${emp.id} - ${emp.name}");
}

Output:

12 - john

Similarly, You can rewrite the getter methods with shorter syntax. arrow(=>) function to replace existing function with shorter syntax expression.

  int get id => _eid;

Here is an example program

class Employee {
  int _eid;
  String _name;

  int get id => _eid;

  set id(int eid) {
    _eid = eid;
  }

  String get name => _name;

  set name(String name) {
    _name = name;
  }
}

void main() {
  Employee emp = Employee();
  emp.id = 12;
  emp.name = "john";

  print("${emp.id} - ${emp.name}");
}

Similarly, can use setters and getters for private members in library.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart| Flutter How to get extension name and MIME type of a file with example

Dart| Flutter How to: Create a private variable with example