Learn/Dart/6. Functions
Lesson 6 of 8
Sign in

Dart, lesson 6

Functions

You've been writing one function all along: main. Now you'll write your own. A function gives a name to a piece of work so you can reuse it, test it in your head, and keep main short.

Read the first line left to right: the function returns an int, is called square, and takes one int parameter named n. return sends the result back to whoever called it and ends the function right there.

A function that does something but gives nothing back has the return type void:

Functions are declared at the top level of the file, next to main, and the order doesn't matter: can call a function written below it.

2 exercises to try what you just read.

Exercise 1

Rectangle helper

Press Ctrl Enter or Check to test your code.

Exercise 2

Order line

Press Ctrl Enter or Check to test your code.

main

Arrow syntax

When a function's body is a single expression, you can write it with =>. These two are the same:

Named and optional parameters

Plain parameters are positional: callers must pass them in order. Dart also supports named parameters, written in curly braces. Callers write the name, which makes calls easy to read, and you can give defaults:

Named parameters are optional unless you mark them required, as in {required String to}. Square brackets make positional parameters optional instead: String tag(String text, [String mark = '!']).

Scope

Variables created inside a function exist only inside that function. Two functions can each have their own total without interfering. A function sees its own parameters and locals, plus anything declared at the top level of the file:

Passing values in through parameters and getting results out through return keeps functions independent. That makes them easier to reuse and reason about than functions that reach out and change shared variables.

Functions are values

You can store a function in a variable or pass it to another function. Small unnamed functions are common for this:

Further reading

  • Functions

Write two functions: area(int width, int height) returning the area, and perimeter(int width, int height) returning the perimeter. Read width and height on one line separated by a space, and print both results using your functions.

Input:

Output:

Write a function orderLine(String item, {int qty = 1, String unit = 'pcs'}) that returns a string like 3 kg apples. In main, read three lines: an item name, a quantity and a unit. Print the item with all values passed, then print it again calling orderLine with only the item name, so the defaults are used.

Input:

Output:

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

void main() {
  print(square(4)); // 16
  print(square(9)); // 81
}
void greet(String name) {
  print('Hi, $name!');
}
bool isEven(int n) {
  return n % 2 == 0;
}

bool isEven2(int n) => n % 2 == 0;
String brew(String drink, {int sugars = 0, bool large = false}) {
  final size = large ? 'large' : 'small';
  return '$size $drink with $sugars sugar(s)';
}

void main() {
  print(brew('tea'));                       // small tea with 0 sugar(s)
  print(brew('coffee', large: true, sugars: 2));
}
const taxRate = 0.2; // top level: visible everywhere

double withTax(double price) {
  final tax = price * taxRate; // 'tax' only exists in here
  return price + tax;
}
final twice = (int x) => x * 2;
print(twice(21)); // 42

final shouted = ['hi', 'yo'].map((w) => w.toUpperCase()).toList(); // [HI, YO]
4 7
Area: 28
Perimeter: 22
apples
3
kg
3 kg apples
1 pcs apples