Skip to content

Beginner · Dart basics · topic 4 of 50 · 30 min

Functions

Explanation

Functions have a return type, a name and parameters. Short ones use arrow syntax: int square(int n) => n * n. Parameters can be positional, optional positional in [ ], or named in { }, where named ones can be required or have defaults. Functions are values: you can pass anonymous functions as arguments, which is exactly how Flutter's onPressed: () { ... } works.

Why functions?

A function is a named, reusable block of code that does one job. Write the GST calculation once, call it from ten screens, and fix it in one place when rules change.

dart
double withGst(double price, double ratePercent) {
  return price + price * ratePercent / 100;
}

int square(int n) => n * n;       // arrow syntax for one expression

void greet(String name) {
  print('Namaste, $name!');
}

void main() {
  print(withGst(1000, 18));   // 1180.0
  print(square(9));           // 81
  greet('Kiran');
}
The return type comes first (double, int, void). => expr is short for { return expr; }.

Named parameters

Named parameters are wrapped in curly braces and passed by name. They make calls readable, and Flutter uses them everywhere: Text('Hi', style: ..., maxLines: 2). A named parameter is optional unless marked required; optional ones need a default value or a nullable type.

dart
String ticket({required String from, required String to, int passengers = 1, String? coach}) {
  final coachText = coach == null ? '' : ' in $coach';
  return '$passengers ticket(s) $from to $to$coachText';
}

void main() {
  print(ticket(from: 'Pune', to: 'Nagpur'));
  print(ticket(to: 'Goa', from: 'Mumbai', passengers: 3, coach: '3A'));
}
Order of named arguments does not matter. required ones must be given.

Named parameters are the main reason Flutter code is readable. Compare Container(16, null, Colors.white) with Container(padding: EdgeInsets.all(16), color: Colors.white): the second tells you exactly what each value means.

Optional positional parameters

dart
String greeting(String name, [String title = '']) =>
    title.isEmpty ? 'Hello $name' : 'Hello $title $name';

void main() {
  print(greeting('Rao'));          // Hello Rao
  print(greeting('Rao', 'Dr.'));   // Hello Dr. Rao
}
Square brackets make trailing positional parameters optional.
KindSyntaxCall
Positional (required)f(int a)f(1)
Optional positionalf([int a = 0])f() or f(1)
Namedf({int a = 0})f() or f(a: 1)
Required namedf({required int a})f(a: 1)

Functions as values

In Dart, functions are objects. You can store them in variables, pass them to other functions and return them. An anonymous function has no name: (x) => x * 2 or () { print('tapped'); }. This is how Flutter callbacks work: ElevatedButton(onPressed: () { ... }) passes an anonymous function that runs when the button is tapped.

dart
void repeatTimes(int n, void Function(int) action) {
  for (var i = 1; i <= n; i++) {
    action(i);
  }
}

void main() {
  repeatTimes(3, (i) => print('Reminder $i: pay electricity bill'));
  final discounts = [0.1, 0.2];
  final apply = discounts.map((d) => 1000 - 1000 * d).toList();
  print(apply);    // [900.0, 800.0]
}
void Function(int) is the type of a function that takes an int and returns nothing.

You can also name a function type with typedef, for example typedef PriceRule = int Function(int price);, and then write PriceRule rule instead of the long type.

Closures

A closure is a function that remembers variables from where it was created. Flutter widgets use closures all the time, for example a button's onPressed changing a counter defined outside it.

dart
Function makeCounter() {
  var count = 0;
  return () => ++count;
}

void main() {
  final next = makeCounter();
  next();
  print(next());   // 2
}
The returned function keeps its own count.
Think of it like this: Named parameters are like a form with labelled boxes (From, To, Passengers). You can fill the boxes in any order and leave optional ones blank. Positional parameters are like a phone number: the order of digits is everything.

Common mistakes

  • Forgetting required on a named parameter that must be given, then dealing with nulls everywhere.
  • Writing onPressed: doSomething() instead of onPressed: doSomething (or () => doSomething()): the first calls the function immediately while building.
  • Using arrow syntax for a body with several statements. => takes exactly one expression.
  • Missing return types on public functions. Write them; they document the code.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Functions · 1/6

double withGst(double price, double rate) {
  return price + price * rate / 100;
}

A function has a return type, a name and parameters.

Prefer a video by a teacher? Find free videos on “dart functions named parameters optional arrow anonymous functions” on YouTube ↗

In real life: A price formatter used across an app

A clothing store app shows prices on product cards, the cart and invoices. One function formatPrice(paise, {bool showPaise = true, String symbol = '₹'}) handles all of them with named options, so every screen formats money the same way.

dart
String formatPrice(int paise, {bool showPaise = true, String symbol = '₹'}) {
  final rupees = paise ~/ 100;
  final rest = (paise % 100).toString().padLeft(2, '0');
  return showPaise ? '$symbol$rupees.$rest' : '$symbol$rupees';
}

void main() {
  print(formatPrice(129900));                    // ₹1299.00
  print(formatPrice(129900, showPaise: false));  // ₹1299
}
Named options keep calls readable.

Practice (0/3 done)

Task 1 · Question

What does this print? int calc(int a, {int b = 2, int c = 3}) => a * b + c; void main() { print(calc(5, c: 10)); }

Task 2 · Question

Which is the correct way to give a button a callback?

Task 3 · Practice

Write emi({required double principal, double yearlyRate = 9, int months = 12}) that returns the EMI, and applyToAll(List<int> prices, int Function(int) rule) that returns a new list. Call emi in three ways and applyToAll with two different anonymous functions.

Quick quiz

Question 1

1.How are named parameters declared?

Question 2

2.What does => mean in a function?

Question 3

3.An optional named parameter without a default must be…

Question 4

4.What is a closure?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

How are named parameters declared?

Answer: In curly braces

{ } declares named parameters.

What does => mean in a function?

Answer: Return the single expression that follows

Arrow syntax returns one expression.

An optional named parameter without a default must be…

Answer: Nullable

With null safety it needs a default or a nullable type.

What is a closure?

Answer: A function that remembers variables from where it was created

Closures capture their surroundings.

def power(n, p=2): return n ** p. What is power(3)?Related

Answer: 9

p is left out, so the default 2 is used: 3 ** 2 = 9.

From Parameters, arguments and defaults

A variable is declared with const inside a function. Where can it be used?Related

Answer: Only inside that function

let and const are block-scoped: they live only inside their { }.

From Functions

Which is a valid function type for "takes two ints and returns a bool"?Related

Answer: func(int, int) bool

Function types are written func(params) results.

From Variadic functions, function values and closures

Why are named arguments useful?Related

Answer: They make calls with many parameters clear and order-independent

Names document what each value means.

From Functions

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. This is the last topic of “Dart basics”. The module exam comes next.
  2. Module 1 exam: Dart basics · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Null safety and object-oriented Dart. 50 topics left in the course before the final exam.

← Previous: Control flow and collections