On this page12 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Writing a Function
  4. 2. Parameters: Values In
  5. 3. return: Values Out
  6. 4. Arrow Functions
  7. 5. Functions vs Methods
  8. Code Examples
  9. Common Beginner Mistakes
  10. Practice Questions
  11. Practice Answers
  12. Key Takeaways

Lecture 025: Functions & Methods

Day10: Functions & Parameters
Lecture025 of 057
Estimated video length12 min
TargetDart 3.12
LevelBeginner

Copying the same ten lines into five places means fixing every bug five times. A function gives a block of code a name, so you write it once and use it anywhere. A method is a function that belongs to a class or object. You've been calling them since Lecture 004.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lectures 006–024: variables, strings, collections, conditions and loops.


Learning Objectives

  • Define and call a function
  • Pass a value in with a parameter
  • Send a value back with return, and give the return type
  • Use void for functions that return nothing
  • Write one-line functions with =>
  • Tell functions and methods apart

1. Writing a Function

dart
void greet() {
  print('Hello!');
}

void main() {
  greet();   // call it
  greet();   // and again
}

Output

code
Hello!
Hello!
  • void is the return type: this function gives nothing back.
  • greet is the name.
  • () holds the parameters (none here).
  • { ... } is the body, the code that runs on each call.

main itself is a function: the one Dart calls first.

2. Parameters: Values In

dart
void greetUser(String name) {
  print('Hello, $name!');
}

greetUser('Ayesha');   // Hello, Ayesha!

name is a parameter: a variable that gets its value from the call. 'Ayesha' is the argument, the value passed in. Lecture 026 covers parameters in depth.

3. return: Values Out

dart
int square(int n) {
  return n * n;
}

var result = square(6);
print(result);                   // 36
print(square(3) + square(4));    // 25

The type before the name (int) says what the function gives back. return sends the value back and ends the function immediately.

4. Arrow Functions

When the body is a single expression, use =>:

dart
double areaOfCircle(double radius) => 3.14159 * radius * radius;
bool isEven(int n) => n % 2 == 0;

print(areaOfCircle(2).toStringAsFixed(2));   // 12.57
print(isEven(7));                            // false

=> expression means { return expression; }.

5. Functions vs Methods

A function stands on its own. A method belongs to a class and is called on an object with a dot:

dart
// Standalone function
void greet() {
  print('Hello!');
}

// Method within a class
class Person {
  String name;
  Person(this.name);

  void introduce() {
    print('My name is $name');
  }
}

void main() {
  greet();                 // calling a function

  var person = Person('John');
  person.introduce();      // calling a method: My name is John

  print('hello'.toUpperCase());   // a String method you already know
}

Classes are covered on Day 11. Methods are written just like functions, but inside a class.


Code Examples

Example 1: A Weather Report

dart
double celsiusToFahrenheit(double c) => c * 9 / 5 + 32;

String describeTemperature(double c) {
  if (c >= 35) return 'Hot';
  if (c >= 20) return 'Pleasant';
  return 'Cold';
}

void printReport(String city, double c) {
  var f = celsiusToFahrenheit(c);
  print('$city: ${c}°C = ${f.toStringAsFixed(1)}°F (${describeTemperature(c)})');
}

void main() {
  printReport('Karachi', 34);
  printReport('Murree', 12);
  printReport('Multan', 41);
}

Output

code
Karachi: 34.0°C = 93.2°F (Pleasant)
Murree: 12.0°C = 53.6°F (Cold)
Multan: 41.0°C = 105.8°F (Hot)

Each function does one small job, and printReport calls the other two. Change the formula in one place, and every report uses it.


Common Beginner Mistakes

1. Forgetting return

dart
int square(int n) {
  n * n;
}
code
Error: A non-null value must be returned since the return type 'int' doesn't allow null.

Calculating n * n isn't enough: return n * n;.

2. Using the result of a void function

dart
void greet() {
  print('Hi');
}

var x = greet();
print(x);
code
Error: This expression has type 'void' and can't be used.

void means "nothing comes back". Return a value if you need one.

3. Writing the function inside main below the call

dart
void main() {
  print(square(4));
  int square(int n) => n * n;
}
code
Error: Local variable 'square' can't be referenced before it is declared.

Put functions outside main, at the top level of the file. Then order doesn't matter.

4. Forgetting the brackets: greet; doesn't call the function. greet(); does.


Practice Questions

  1. What does void mean as a return type?
  2. Write a function double half(double x) that returns half of x, using =>.
  3. What's the difference between a parameter and an argument?
  4. What happens to the lines after return in a function?
  5. Is 'hi'.toUpperCase() a function call or a method call?

Practice Answers

  1. The function doesn't return a value.
  2. double half(double x) => x / 2;
  3. The parameter is the variable in the definition (n); the argument is the value in the call (6).
  4. They don't run. return ends the function.
  5. A method call. toUpperCase belongs to String.

Key Takeaways

  • A function is a named, reusable block: returnType name(params) { body }.
  • Call it with name(arguments).
  • return sends a value back and ends the function; void means nothing comes back.
  • => expression is a one-line function body.
  • A method is a function that belongs to a class: object.method().