Skip to main content

Menu

System onlineAI Tutorials / 2026

AI Tutorials
Knowledge search

Recent · Popular · Tutorials

  • dart3 tutorials
  • java1 tutorial
  • Javascript3 tutorials
  • Node.js Introduction2 tutorials
  • dartdart · General · In depth
  • JavascriptJavascript · Advanced · In depth
  • JavascriptJavascript · Advanced · Mid
  • JavascriptJavascript · Advanced · Short

Find a tutorial

Tell the assistant what you want to learn. It suggests published chapters.

For example: “I want to learn Rust ownership from the start.” The conversation is kept only in this tab.

0 / 2,000 characters

Enter to send, Shift+Enter for a new line. Do not include personal information.

Chapter 6

Functions and Parameters

A function is a named block of code that does one job. You give it some input, it does its work, and it may hand back an output. Every time you need that job done, you call the function by name instead of rewriting the same lines.
Level: GeneralLength: In depth4 min read

Read at another depth

Functions and Parameters

What a Function Is

A function is a named block of code that does one job. You give it some input, it does its work, and it may hand back an output. Every time you need that job done, you call the function by name instead of rewriting the same lines.

Think of a vending machine. You press a button (the function name), put in coins (the inputs, called arguments), and get a snack (the return value). The machine's inner workings stay hidden. Functions let you build programs the same way: from small, named parts you can trust without reading.

In Dart, functions are everywhere. Even the simplest program has a function called main, which is where the program starts running. This chapter assumes you have seen variables and basic types from earlier chapters.

Declaring a Function

A Dart function has four parts: a return type (the kind of output), a name, a parameter list (the inputs it expects), and a body (the code that runs).

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

This reads as: a function named add, taking two whole numbers a and b, returning a whole number. If a function returns nothing, its return type is void.

Dart also offers a shorthand for one-line functions, called an arrow function. The => symbol means "return this":

Code example in dart
int add(int a, int b) => a + b;

Both versions do exactly the same thing. The arrow form is just more compact.

Positional Parameters

The parameters you have seen so far are positional. That means the meaning of each argument comes from its position: the first argument fills the first parameter, the second fills the second, and so on. Order matters.

Code example in dart
String fullName(String first, String last) => '$first $last';

void main() {
  print(fullName('Ada', 'Lovelace')); // Ada Lovelace
}

Call it with the arguments swapped and you get a different, probably wrong, result. That is the trade-off of positional parameters: they are short to write, but the caller must know the correct order.

Named Parameters

Dart also supports named parameters. You wrap them in curly braces in the declaration, and callers pass values by name. This makes call sites self-documenting: anyone reading the code sees exactly what each value means.

Code example in dart
void greet(String name, {String prefix = 'Hello'}) {
  print('$prefix, $name!');
}

void main() {
  greet('Ada');                 // Hello, Ada!
  greet('Grace', prefix: 'Hi'); // Hi, Grace!
}

Here name is positional and required. prefix is named and optional, with a default value of 'Hello'. If the caller does not supply it, the default is used.

Two important rules:

  1. Named parameters are optional by default. If you want to force the caller to provide one, mark it required:
Code example in dart
void register({required String email, required int age}) {
  print('$email, $age');
}
  1. You can have both positional and named parameters in one function, but the positional ones must come first, and you cannot mix named parameters with optional positional ones (covered next).

caption: How arguments are matched to parameters before the body runs. alt: A flowchart showing a function call splitting into positional matching by order and named matching by name, both feeding the function body, which produces a return value.

Optional Positional Parameters

A third style exists: optional positional parameters, written in square brackets. They keep the brevity of positional parameters but let callers omit the later ones.

Code example in dart
String tag(String word, [String prefix = '']) => '$prefix$word';

void main() {
  print(tag('hello'));        // hello
  print(tag('hello', '#'));   // #hello
}

You can mix required positional and optional positional parameters, but optional ones must come last. Choose one style per function: either optional positional in brackets or named in braces, not both.

Choosing a Parameter Style

With three styles available, a quick guide helps:

StyleWritten asBest for
Required positional`int a`Few inputs with obvious order, like `(x, y)`
Optional positional`[int a = 0]`Short calls where defaults make sense
Named`{int a = 0}`Many inputs, readability, boolean flags

A common rule of thumb: once a function has more than two or three parameters, or has any true/false flags, switch to named parameters. toggle(visible: true) reads far better than toggle(true).

Functions as Values

In Dart, a function is a value, just like a number or a string. You can store one in a variable, pass one to another function, and return one from a function. A function that takes or returns functions is called a higher-order function.

Code example in dart
void runTwice(void Function() action) {
  action();
  action();
}

void main() {
  runTwice(() => print('tick')); // prints tick twice
}

Look closely at the type void Function(). It means "a function that takes no arguments and returns nothing." You can write the function inline with () => print('tick'); a function written on the spot like this is called an anonymous function, or a lambda in some languages. This idea powers much of Dart, from event handlers to the collection methods you will meet in a later chapter.

Code example in dart
int Function(int) makeDoubler() => (n) => n * 2;

void main() {
  final double_ = makeDoubler();
  print(double_(21)); // 42
}

makeDoubler takes no arguments and returns a function of type int Function(int): something that takes an int and returns an int. Being comfortable reading types like this is a key Dart skill.

Common Mistakes

  • Forgetting required on a named parameter that the body actually needs. The missing value arrives as null and fails later; the required keyword catches the mistake at compile time instead.
  • Putting named or optional parameters before required positional ones. Dart rejects this ordering, and the fix is simply to reorder.
  • Confusing void functions with functions that return a value. A void function's call cannot be used in an expression like print(add(1, 2)) if add returned nothing.
  • Writing arrow functions with multiple statements. => fits exactly one expression; use braces and return for anything longer.

callout note tip: When you hover over a function in the Dart analyzer or read its documentation, the parameter style tells you at a glance how to call it. Braces mean "pass by name," brackets mean "optional, in order," and plain parentheses mean "required, in order."

Putting It Together

Code example in dart
String describe(String name, {int age = 0, String? city}) {
  final place = city ?? 'an unknown city';
  return '$name is $age and lives in $place.';
}

void main() {
  print(describe('Ada', age: 36, city: 'London'));
  print(describe('Alan'));
}

This combines what you have learned: a required positional parameter, a named parameter with a default, a nullable named parameter, and the null-aware ?? operator from the earlier null safety chapter. Small functions like this, each doing one clear job with well-chosen parameters, are the building blocks of every larger Dart program.

exercise Q: Rewrite void order(bool paid, bool express, String item) as a declaration that uses named parameters so calls like order(item: 'book', express: true) work, with paid defaulting to true and express to false. A: void order({required String item, bool paid = true, bool express = false}) — named parameters suit the boolean flags, and item is marked required because the function needs it and it has no sensible default.

exercise Q: What is the type of a variable holding a function that takes one String and returns a bool? A: bool Function(String). For example: bool Function(String) checker = (s) => s.isEmpty;

estimate minutes: 60

Spotted a mistake, or code that does not work?

Report an issue

Chapter: Functions and Parameters

0 / 2,000 characters

Plain text, for example: the second code sample does not compile. Do not include personal information.

You can't do that