thumbnail

Static Methods And Variables in Dart

Published on 29 March 2020
Last Updated on 29 March 2020

Static keyword is used for defining static variables and methods in Dart. Methods and variables that are defined static are accessed using the ClassName in Dart

Static variables or class variables

Static variables are also known as class variables. One thing to note is that static variables are not initialized until they are used.

Static variables are particularly useful for defining constants. Static variables are also useful for defining values that are persistent between two different classes or different instances.

Single copy of static variable is shared amongst different instances of a class.

// program to demonstrate use of static variables in Dart

class Person {
  // constant static variable
  static const name = 'john';

  // static variable
  static var age = 20;
}

main(List<String> args) {
  print('Person.name is ${Person.name}');
  print('Person.age is ${Person.age}');
  // changing value of static variable
  Person.age = 22;
  print('Person.age is ${Person.age}');
}

Above program produces following output:

Person.name is john
Person.age is 20
Person.age is 22

Static methods or class methods

Static methods are also called class methods in Dart. Static methods are encapsulated inside a class to make the code look more modular and readable. Static methods can be defined using the work static.

Static methods can be used as compile time constants.

General syntax for static methods in Dart

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

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

Above method can be called as follows:

ClassName.methodName();

Program to demonstrate use of static 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