thumbnail

Class Methods And Instance Methods in Dart

Published on 29 March 2020
Last Updated on 29 March 2020

Methods In Dart

Methods in Dart are used for providing a specific behaviour to an object. Methods for specific object are encapsulated using Classes.

Class methods in Dart

Class methods are also knows static methods in Dart.

A Class method is encapsulated inside a class for making the code more modular and readable and its definition begins with the keyword static.

General syntax for methods in Dart

Given below is a general syntax used by methods in Dart.

class ClassName{
  static return_type methodName(){
     // statements
  }
}

Above method can be called as follows:

ClassName.methodName();

Program to demonstrate use of Class methods in Dart

// program to demonstrate use of class methods in Dart

class Arithmetic {
  static int add(int a, int b) {
    return a + b;
  }

  static int sub(int c, int d) {
    return c - d;
  }
}

main(List<String> args) {
  var addition = Arithmetic.add(2, 3);
  var subtraction = Arithmetic.sub(5, 2);
  print('Addition is: ${addition}');
  print('Subtraction is: ${subtraction}');
}

Above program produces following output:

Addition is: 5
Subtraction is: 3

Difference between methods and functions in Dart

Methods in Dart are encapsulated in a specific class whereas functions in Dart are top level. Top level functions don’t require to be declared as static.

Instance Methods

Instance methods in Dart are all methods that are not declared using the keyword static. All non static methods in Dart are instance methods.

General syntax for declaring instance methods in Dart

Given below is a general syntax used by instance methods in Dart.

class ClassName{
  return_type methodName(){
     // statements
  }
}

Above method can be called as follows:

var instance=ClassName();
instance.methodName();

Program to demonstrate how to define and call instance methods in Dart

// program to demonstrate use of class methods in Dart

class Arithmetic {
  // constructor
  Arithmetic(this.a, this.b);

  // fields
  int a;
  int b;

  // add two numbers
  int add() {
    return a + b;
  }

  // subtract two numbers
  int sub() {
    return a - b;
  }
}

main(List<String> args) {
  var ar = new Arithmetic(4, 2);
  var addition = ar.add();
  var subtraction = ar.sub();

  print('addition is: ${addition}');
  print('subtraction is: ${subtraction}');
}

Above program produces following output:

addition is: 6
subtraction is: 2

We hope that you found this guide useful for learning class methods and instance methods in Dart.