What is a function?
A function is a named block of code that does one job. You write it once and call it whenever you need it. main is a function; so are print and int.parse.
Functions make programs shorter (no copy-paste), easier to read (the name says what the code does) and easier to fix (change one place).
void greet() {
print('Welcome to BrainBit Infotech!');
}
void main() {
greet();
greet();
}
Welcome to BrainBit Infotech!
Welcome to BrainBit Infotech!
Parameters and return values
Parameters are the inputs a function declares; arguments are the values you pass in the call. The type before the name is the return type; void means nothing is returned.
double area(double length, double width) {
return length * width;
}
void main() {
print(area(12.5, 8));
double a = area(3, 4);
print('Area: $a');
}
100.0
Area: 12.0
return sends the value back and ends the function at once.
Optional positional parameters [ ]
Parameters inside square brackets may be left out. Give each a default value, or make its type nullable.
String fullName(String first, [String last = '', String? title]) {
final t = title == null ? '' : '$title ';
return '$t$first $last'.trim();
}
void main() {
print(fullName('Asha'));
print(fullName('Asha', 'Kumari'));
print(fullName('Asha', 'Kumari', 'Dr.'));
}
Asha
Asha Kumari
Dr. Asha Kumari
Named parameters { }
Named parameters are passed by name, in any order. They make calls self-explaining, which is why Flutter uses them everywhere.
double bill({required double price, int qty = 1, double gstPercent = 18}) {
final base = price * qty;
return base + base * gstPercent / 100;
}
void main() {
print(bill(price: 100));
print(bill(price: 100, qty: 3));
print(bill(qty: 2, price: 50, gstPercent: 5));
}
118.0
354.0
105.0
requiredmeans the caller must pass it.- A named parameter without
requiredneeds a default or a nullable type. - You cannot mix optional positional
[ ]and named{ }parameters in one function.
Arrow functions
When the body is a single expression, => expression replaces { return expression; }:
int square(int n) => n * n;
bool isEven(int n) => n % 2 == 0;
void main() {
print(square(9));
print(isEven(7));
}
81
false
Anonymous functions and callbacks
Functions are values in Dart: you can store them in variables and pass them to other functions. A function with no name is an anonymous function (or lambda).
void repeat(int times, void Function(int) action) {
for (int i = 1; i <= times; i++) {
action(i);
}
}
void main() {
var double = (int x) => x * 2;
print(double(21));
repeat(3, (i) {
print('Round $i');
});
List<int> marks = [45, 82, 29, 67];
print(marks.where((m) => m >= 33).toList());
}
42
Round 1
Round 2
Round 3
[45, 82, 67]
The function you pass in, here (i) { ... }, is a callback: the receiving function calls it back when it needs to. Flutter buttons work the same way: onPressed: () { ... }.
void Function(int) is the type of a function that takes an int and returns nothing. A typedef gives such a type a name: typedef Action = void Function(int);.
Scope
A variable declared inside a function or a block { } exists only there. A function can read variables from the blocks around it; an inner function that keeps using them is a closure:
Function makeCounter() {
int count = 0;
return () {
count++;
return count;
};
}
void main() {
var next = makeCounter();
print(next());
print(next());
print(next());
}
1
2
3
Recursion
A recursive function calls itself. It needs a base case that stops the calls.
int factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}
void main() {
print(factorial(5));
print(factorial(10));
}
120
3628800
Without a base case the calls never end and Dart throws a StackOverflowError.
Example: a reusable EMI calculator
import 'dart:math';
double emi({required double loan, required double yearlyRate, required int months}) {
final r = yearlyRate / 12 / 100;
return loan * r * pow(1 + r, months) / (pow(1 + r, months) - 1);
}
void main() {
final e = emi(loan: 500000, yearlyRate: 9, months: 60);
print('Monthly EMI: Rs ${e.toStringAsFixed(2)}');
}
Monthly EMI: Rs 10379.18
Common mistakes
- Forgetting
returnin a function with a return type: Dart reports that the function can complete without returning a value. - Calling a named parameter by position:
bill(100)is an error; writebill(price: 100). - Passing
print()(a call) instead ofprint(the function) as a callback. - Writing
=>with a block:=> { ... }is wrong; use either=> expror{ ... }. - Recursion without a base case.
Key points
- A function has a return type, a name, parameters and a body;
voidreturns nothing. [ ]marks optional positional parameters;{ }marks named ones;requiredforces a named one.- Defaults are written with
=. => expris short for{ return expr; }.- Functions are values: store them, pass them as callbacks, return them (closures).
- Recursive functions need a base case.
Practice questions
1. Write a function maxOf3(int a, int b, int c) that returns the largest number.
import 'dart:math';
int maxOf3(int a, int b, int c) => max(a, max(b, c));
void main() {
print(maxOf3(4, 19, 7)); // 19
}2. Write greet({required String name, String city = 'Ranchi'}) and call it twice, once without the city.
void greet({required String name, String city = 'Ranchi'}) {
print('Hello $name from $city');
}
void main() {
greet(name: 'Rohit');
greet(name: 'Meena', city: 'Patna');
}3. What is printed? int f(int n) => n < 2 ? n : f(n - 1) + f(n - 2); print(f(7));
13. f is the Fibonacci function: 0, 1, 1, 2, 3, 5, 8, 13.
4. Write a function applyTwice that takes an int and a function and applies the function two times.
int applyTwice(int x, int Function(int) f) => f(f(x));
void main() {
print(applyTwice(3, (n) => n * 10)); // 300
}5. Why is bill(100) an error for double bill({required double price})?
price is a named parameter, so it must be passed with its name: bill(price: 100).