Instance method in Dart with examples

Published by admin on

Instance methods in Dart :

In simple words, instance methods are methods defined in a class those are available with class objects. Instance methods can access to instance variables and this. For example, let’s consider the below program :

class Student {
  final String name;
  final num age;

  const Student(, this.age);

  bool isAgeEven() {
    return age % 2 == 0;

main() {
  var alex = Student("Bob", 30);

  print("isEven : ${alex.isAgeEven()}");

Here, isAgeEven is an instance method to check if the age of a Student is even or not. It returns one boolean value.

Using getter and setter methods :

Getter and Setter methods are used to get or read variables and set or write variables. These methods are written using get and set keywords.

class Student {
  final String name;
  num age;


  set setAge(num age) => this.age = age;
  num get getAge => this.age;

main() {
  var alex = Student("Bob");
  alex.setAge = 10;
  print("Age : ${alex.getAge}");

Dart instance method

Each instance variables has an implicit getter and setter. You can use . to get/set one instance variable.

Similar tutorials :

Categories: dart


Leave a Reply

Your email address will not be published. Required fields are marked *