{

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 Example - Program to check Leap year or not

Dart/Flutter How to Check string contains alphabetic number

Dart| Flutter How to check element exists in Array

Dart| Flutter How to: Convert Map to Query String with example

Dart| Flutter How to: Multiple ways to get the First and last letter of a string

Dart| Flutter: How to Convert timestamp epoch to DateTime local and UTC| Flutter By Example

Dart| Flutter: How to Convert timestamp string from 24 hours to 12 hour format| Flutter By Example