Thuta Learning
BasicProgrammingbeginner

Functions

Relax. We'll talk through this in plain words — no textbook voice.

A function is a named, reusable chunk of logic. Using functions keeps your code shorter, easier to read, and easier to reuse.

dart
int add(int a, int b) {
  return a + b;
}

String buildGreeting({required String name, String message = 'Hello'}) {
  return '$message, $name!';
}

void main() {
  print('Sum: ${add(2, 3)}');
  print(buildGreeting(name: 'Aung Aung'));
  print(buildGreeting(name: 'Mya Mya', message: 'Welcome'));
}

add takes in two numbers and returns the result. buildGreeting uses named parameters, which makes it easy to tell what each argument means when you call the function.

You should see
Sum: 5 Hello, Aung Aung! Welcome, Mya Mya!

Easy traps

  • A common mistake is expecting a result from a function that never has a return statement. A void function doesn't return a value.
Functions | Thuta Learning