Beginner · Dart basics · topic 4 of 50 · 30 min
Functions
Explanation
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.
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');
}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.
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'));
}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
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
}| Kind | Syntax | Call |
|---|---|---|
| Positional (required) | f(int a) | f(1) |
| Optional positional | f([int a = 0]) | f() or f(1) |
| Named | f({int a = 0}) | f() or f(a: 1) |
| Required named | f({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.
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]
}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.
Function makeCounter() {
var count = 0;
return () => ++count;
}
void main() {
final next = makeCounter();
next();
print(next()); // 2
}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.
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
}Practice (0/3 done)
What does this print? int calc(int a, {int b = 2, int c = 3}) => a * b + c; void main() { print(calc(5, c: 10)); }
Which is the correct way to give a button a callback?
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Parameters, arguments and defaultsPython Programming · Functions
- FunctionsFrontend Web Development · JavaScript basics
- Variadic functions, function values and closuresGo Programming (backend and cloud) · Control flow and functions
- FunctionsKotlin and Android App Development · Null safety, functions and lambdas
- Parameters in depth: optional, named, ref, out, params, overloadingC# and .NET · Decisions, loops and methods
- FunctionsC Programming (from zero to systems) · Functions and arrays
Questions people ask about this
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.
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.
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
- This is the last topic of “Dart basics”. The module exam comes next.
- Module 1 exam: Dart basics · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Null safety and object-oriented Dart. 50 topics left in the course before the final exam.