Thuta Learning
Dart
BasicProgrammingBeginner

Functions

DartLesson 735 min

What you'll walk away with

  • Declare a function with a return type and call it with positional arguments
  • Choose between required positional, optional positional [ ] and named { } parameters, using required and default values
  • Write arrow functions and explain what a closure captures
  • Store a function in a variable and pass it to another function such as map

Explain it simply

Explain it simply

Think of a function as a recipe card. The card has a name, a list of the ingredients it needs (the parameters), and a description of the dish you get at the end (the return value). Whoever wants the dish, the caller, just hands over the ingredients and receives the result without rethinking the method.

In Dart, functions are ordinary values too: you can keep one in a variable, hand it to another function, or have a function return a new function. Later in this lesson you will see each of those abilities one step at a time.

Problem → Why → Solution

The problem: pasted logic and unreadable calls

The code below pastes the same price-with-tax rule into three places. When the tax rate changes you must find all three, and if you miss one, a page shows the wrong price. The second problem is sendInvite('Aye', 25, true, false): unless you reopen the declaration, you cannot tell what true and false mean.

shop.dart
void sendInvite(String name, int age, bool admin, bool notify) {
  // ...
}

void main() {
  // The same tax rule pasted three times
  print('Total: ' + (12000 * 1.05).toStringAsFixed(0) + ' MMK');
  print('Total: ' + (4500 * 1.05).toStringAsFixed(0) + ' MMK');
  print('Total: ' + (800 * 1.05).toStringAsFixed(0) + ' MMK');

  // Which boolean is admin and which is notify?
  sendInvite('Aye', 25, true, false);
}

What does a function fix here?

Putting the rule in one function leaves a single place to change, and the name says what it does. Named parameters solve the second problem: sendInvite(name: 'Aye', admin: true, notify: false) explains itself at every call site.

Core concept: anatomy and the three kinds of parameter

A function has a return type, a name, a parameter list in parentheses and a body in curly braces. A return type of void means no value comes back. If any path through a non-void function lacks a return, Dart refuses to compile it; for example, returning only inside an if gives "A non-null value must be returned since the return type 'int' doesn't allow null." You may omit the return type, but you should always write it on public functions.

There are three kinds of parameter. Required positional parameters (int add(int a, int b)) depend on count and order; calling add(1) reports "Too few positional arguments: 2 required, 1 given." Optional positional parameters go inside [ ] after the required ones (String shout(String text, [int level = 1])) and need either a default value or a nullable type (int?). Named parameters go inside { } and callers pass them as name: value in any order. Named parameters are optional by default; write required when one must be supplied. Declaring { String name } with a non-nullable type, no default and no required fails with "The parameter 'name' can't have a value of 'null' because of its type 'String', but the implicit default value is 'null'." You cannot mix [ ] and { } in the same function.

When the body is a single expression you can use arrow syntax: int square(int x) => x * x; means exactly the same as { return x * x; }. After => you cannot put a block of statements; for anything longer than one expression use a normal { } body.

Functions are objects, so you can store them in variables, pass them as arguments and return them from other functions. A function type is written int Function(int), meaning takes an int and returns an int. Anonymous functions such as (n) => n * 2 are what you hand to methods like map, where and sort. A function can also capture the variables visible where it was created, which is what makes it a closure; the captured variables are the real variables, not copies, so they stay alive after the enclosing function has finished.

Arguments are passed as references to objects. Reassigning a parameter inside the function does not touch the caller's variable, but if the parameter is a list, adding to it changes the very same list the caller can see.

Mental model: a recipe card
  1. Caller supplies the arguments
  2. Parameters bind by position or name
  3. Body runs and may use captured values
  4. return hands back one value

The kind of parameter decides how callers must write the call, and the return type promises what comes back.

General pattern

dart
ReturnType name(Type first, [Type second = fallback]) {
  return value;
}

ReturnType named({required Type a, Type b = fallback}) => expression;

ReturnType Function(Type) holder = name;

The first shape is an ordinary function with a block body, one required positional parameter and one optional [ ] parameter. The second uses named { } parameters with the => arrow. The last line stores a function in a variable, written with a Function type.

Example: positional, named, optional and a closure

This example uses all three kinds of parameter plus one closure. add takes two required positional parameters, buildGreeting takes named parameters (name is required, message has a default), and shout has an optional positional one. makeCounter returns a counter function that goes up by one every time it is called.

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

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

String shout(String text, [int level = 1]) => text.toUpperCase() + '!' * level;

int Function() makeCounter() {
  int count = 0;
  return () {
    count++;
    return count;
  };
}

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

  var next = makeCounter();
  print(next());
  print(next());
}

Code breakdown

  1. Line 1int add(int a, int b) {

    Return type int, name add and two required positional parameters. Calling add(1) is a compile error because an argument is missing.

  2. Line 5String buildGreeting({required String name, String message = 'Hello'}) {

    These are named parameters inside { }. name is marked required, so omitting it is a compile error, while message has the default 'Hello' and may be left out.

  3. Line 9String shout(String text, [int level = 1]) => text.toUpperCase() + '!' * level;

    A bracketed optional positional parameter. The => makes the single expression the return value, and '!' * level repeats the exclamation mark level times.

  4. Line 11int Function() makeCounter() {

    The return type int Function() means this function returns another function, one that takes no arguments and returns an int.

  5. Line 14count++;

    The returned anonymous function captures the count variable from makeCounter and keeps modifying it even after makeCounter has finished.

  6. Line 21print(buildGreeting(name: 'Aung Aung'));

    Named arguments are written name: value. Because message is omitted, its default 'Hello' is used and the output is Hello, Aung Aung!

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

Positional, optional positional or named?

StyleSyntaxBest for
Required positional(int a, int b)One or two arguments whose meaning is obvious
Optional positional(String t, [int n = 1])One trailing argument that may be left out
Named({required String n, bool on = false})Three or more arguments, and boolean flags

The Effective Dart guidelines advise against positional boolean parameters, because a call like sendInvite('Aye', 25, true, false) reveals nothing about what the booleans mean. The code below shows an optional positional parameter (weightLabel), a nullable named parameter (stock) and a named boolean with a default (onSale) side by side. Notice that productLine can be called without remembering the argument order.

parameters.dart
String weightLabel(double value, [String unit = 'kg']) => '$value $unit';

String productLine({required String name, int? stock, bool onSale = false}) {
  final stockText = stock == null ? 'unknown stock' : '$stock in stock';
  final saleText = onSale ? ' (on sale)' : '';
  return '$name - $stockText$saleText';
}

void main() {
  print(weightLabel(2.5));
  print(weightLabel(2.5, 'lb'));
  print(productLine(name: 'Tea'));
  print(productLine(onSale: true, stock: 12, name: 'Rice'));
}

Functions as values, and closures

Writing typedef Transform = int Function(int); gives a function type a name, which makes parameter lists easier to read. applyTwice takes a Transform and calls it twice; you can pass it a named function such as triple or an anonymous one such as (n) => n - 1. makeAdder returns a new function that has captured step. Finally, the anonymous function passed to list.map(...) converts each element; map is lazy, so notice the .toList() that turns the result into a list.

function_values.dart
typedef Transform = int Function(int);

int applyTwice(Transform action, int start) => action(action(start));

int triple(int n) => n * 3;

Transform makeAdder(int step) => (int n) => n + step;

void main() {
  print(applyTwice(triple, 2));
  print(applyTwice((n) => n - 1, 10));

  final addTen = makeAdder(10);
  print(addTen(5));

  final prices = [100, 250, 40];
  final withTax = prices.map((p) => p + p ~/ 10).toList();
  print(withTax);
}

Each closure gets its own state

Calling makeCounter() twice creates two separate count variables. Even if you call the first counter three times, the first call of the second counter still returns 1. That is why closures behave like tiny objects that keep their own state.

In real projects

Where this shows up in real projects

Almost every Flutter widget is built with named parameters, as in Text('Hi', maxLines: 2) and Padding(padding: ..., child: ...), so nobody has to remember an argument order. A button's onPressed: () { ... } is a closure that captures surrounding state and runs only when the button is pressed. Future.delayed(Duration(seconds: 1), () => ...) and test('name', () { ... }) follow the same pattern of passing a function as an argument.

On the server side, each route handler is just a function that you give to the framework and it calls when a request arrives. Data pipelines such as list.where(...).map(...) chain functions together. In the public API of a Dart package, return types and named parameters act as documentation, so library authors choose required and default values carefully. Keeping each function to one job also makes it easy to test.

Common mistakes

Common mistakes

1. Forgetting required or a default on a named parameter

Writing String greet({String name}) fails with "The parameter 'name' can't have a value of 'null' because of its type 'String', but the implicit default value is 'null'." There are three fixes: add required, give a default, or make it String? and handle null in the body.

2. Passing a named parameter positionally

Calling buildGreeting('Aye') gives "Too many positional arguments: 0 allowed, but 1 found." Parameters inside { } can only be supplied by name, so the call must be buildGreeting(name: 'Aye').

3. Writing a { } block after an arrow

Writing int square(int x) => { return x * x; }; makes Dart read the { } as a set literal rather than a function body, producing errors that include "A value of type 'Set<int>' can't be returned from a function with return type 'int'." After => write a single expression, or drop the arrow and use a normal body.

4. Missing a return on one path

int pick(int a) { if (a > 0) { return a; } } does not compile, because nothing is returned when a is zero or negative. Decide what that case should return and add it, or change the return type to int? and return null.

Best practices

Best practices

  • Choose named parameters when a function has more than about three parameters or any boolean flag.
  • Write return types on every public function; inference is fine for tiny private helpers.
  • Give each function one job and start its name with a verb (calculateTotal, sendInvite).
  • When you can pass a function directly, as in map(square), prefer that over the longer map((n) => square(n)).

Mini challenge

Mini challenge: a pricing toolkit

Write three functions for a shop, each using a different kind of parameter, and then build a closure that calculates tax.

  • String describe(String item, [int qty = 1]): return text like '3 x rice', using 1 when qty is omitted
  • double discounted(double price, {double percent = 10}): subtract the given percentage from the price and return the result
  • double Function(double) makeTaxer(double rate): return a function that adds the tax to a price
  • In main, print both describe calls, both discounted calls, and a taxer with rate 0.25 applied to 80
toolkit.dart
String describe(/* TODO: item, optional qty with a default */) {
  // TODO: return text like '3 x rice'
}

double discounted(/* TODO: price, named percent with a default */) {
  // TODO: subtract the percentage from the price
}

double Function(double) makeTaxer(double rate) {
  // TODO: return a function that adds the tax to a price
}

void main() {
  // TODO: print describe('tea') and describe('rice', 3)
  // TODO: print discounted(200) and discounted(200, percent: 25)
  // TODO: build a taxer for 0.25 and print its result for 80
}

Expected: 1 x tea 3 x rice 180.0 150.0 100.0

Show hint

Put the optional positional parameter in [ ] and the named one in { }. Inside makeTaxer, return an anonymous function such as (double price) => ...; it captures rate from outside itself.

Show solution
toolkit.dart
String describe(String item, [int qty = 1]) => '$qty x $item';

double discounted(double price, {double percent = 10}) {
  return price - price * percent / 100;
}

double Function(double) makeTaxer(double rate) {
  return (double price) => price + price * rate;
}

void main() {
  print(describe('tea'));
  print(describe('rice', 3));
  print(discounted(200));
  print(discounted(200, percent: 25));
  final addTax = makeTaxer(0.25);
  print(addTax(80));
}

Quick quiz 1 / 3

Given String greet({required String name, String message = 'Hi'}), which call compiles?

Quick quiz 2 / 3

With int Function() make() { int n = 0; return () => ++n; }, what do final a = make(); final b = make(); print(a()); print(a()); print(b()); print?

Quick quiz 3 / 3

Which is a valid arrow function that squares x?

What to remember

  • A function has a return type, a name, a parameter list and a body, and every path of a non-void function must return a value.
  • Parameters are required positional, optional positional [ ] or named { }; named ones need required, a default or a nullable type.
  • => is shorthand for a function whose body is a single expression; it cannot hold a block.
  • Functions are values, and a closure captures variables from where it was created and keeps its own state across calls.

Dart language overview — Dart

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Functions | Thuta Learning