Question #222EasyGeneral

What is the difference between Method and function?

Answer

Overview

In Dart (and most programming languages), functions and methods are both blocks of reusable code, but they differ in where they are declared and how they are called.


Function — Standalone, Not Tied to a Class

A function exists independently at the top level (or inside another function).

dart
// Top-level function — not inside any class
int add(int a, int b) {
  return a + b;
}

// Arrow function (shorter syntax)
int multiply(int a, int b) => a * b;

// Calling a function
void main() {
  print(add(3, 4));       // 7
  print(multiply(3, 4));  // 12
}

Method — Function Inside a Class

A method is a function defined inside a class. It has access to the class's fields via

text
this
.

dart
class Calculator {
  // Method — inside a class, has access to 'this'
  int add(int a, int b) {
    return a + b;
  }

  // Instance method using class field
  double _result = 0;
  void setResult(double value) {
    _result = value; // 'this._result' implicitly
  }

  double getResult() => _result;
}

// Calling a method — needs an instance
final calc = Calculator();
print(calc.add(3, 4));         // 7
calc.setResult(42.0);
print(calc.getResult());       // 42.0

Key Differences

FeatureFunctionMethod
LocationTop-level or nestedInside a class
Access to class❌ No
text
this
✅ Has
text
this
How to call
text
functionName()
text
object.methodName()
TypeFirst-class valueTied to class

Special Method Types

dart
class MyClass {
  // Constructor — special method called on creation
  MyClass(this.value);
  final int value;

  // Getter — accessed like a property
  int get doubled => value * 2;

  // Setter
  set doubled(int v) => print('Setting: $v');

  // Static method — called on class, not instance
  static MyClass create(int v) => MyClass(v);

  // Operator — overrides operators
  MyClass operator +(MyClass other) => MyClass(value + other.value);

  // Override toString
  
  String toString() => 'MyClass($value)';
}

Functions as First-Class Values

In Dart, functions are first-class — they can be stored in variables and passed around:

dart
// Store function in variable
int Function(int, int) operation = add; // Regular function
operation = (a, b) => a * b;           // Lambda (anonymous function)

// Pass function as argument
void apply(int a, int b, int Function(int, int) fn) {
  print(fn(a, b));
}
apply(3, 4, add);         // 7
apply(3, 4, (a, b) => a * b); // 12

Summary: A function is a standalone block of code. A method is a function that belongs to a class and can access the class's state via

text
this
. In Dart, the distinction is where they are declared.