{

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


 setter and getter  fields or members variables in a class  in Dart

Setters and Getters 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, and 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 the 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 an existing function with a 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 the 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

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart Example - Program to check Leap year or not