Using Static Methods in Dart and Flutter

Last updated on October 1, 2021 A Goodman Loading... Post a comment

In Dart and Flutter, a static method (or static function) is a method defined as a member of a class but can be directly called without creating an object instance via the constructor. In other words, a static method is a port of a class instead of being a part of a specific instance.

Syntax:

class MyClass {
  static void method1(){
     /* ... */
  }
 
  static String method2(){
    /*...*/
    return "Some string";
  }
}

// Call static methods
void main(){
  MyClass.method1();
  String s = MyClass.method2();
}

Example:

// main.dart
class ExampleClass {
  static void sayHello() {
    print("Hello buddy");
  }

  static int sum(int input1, int input2) {
    return input1 + input2;
  }
}

void main() {
  ExampleClass.sayHello();

  final int sum = ExampleClass.sum(10, 11);
  print(sum);
}

Output:

Hello buddy
21

You can see how static methods are used in this practical guide: Flutter & SQLite: CRUD Example.

Further reading:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like