Functions are reusable blocks of code that perform a specific task. Instead of writing the same code twice, you write a function once and call it whenever you need it.
1. Anatomy of a Function
A function is a self-contained block of code. In Dart, you should always specify the return type and parameter types for safety.
Full Declaration
1// ReturnType FunctionName(Parameters)2bool isEven(int number) {3 return number % 2 == 0;4}5 6void main() {7 print(isEven(10)); // true8}HintIf a function does not return anything, use void. If the body is one line, you can use => arrow syntax (more on that later).
2. Positional vs Named Parameters
Params can be Positional (order matters) or Named (order doesn't matter, easier to read).
Comparison
1// Positional (Strict order)2void printInfo(String name, int age) {3 print('$name is $age');4}5// Call: printInfo('Alice', 25);6 7 8// Named (Readable, order irrelevant)9void printDetails({required String name, required int age}) {10 print('$name is $age');11}12// Call: printDetails(age: 25, name: 'Alice');HintFlutter widgets use Named Parameters almost exclusively because they are much clearer when you have many arguments.
3. Optional & Default Values
Sometimes you want a parameter to be optional. You can mark it as nullable OR give it a default value.
Handling Missing Inputs
1// Optional Positional using []2void greet(String name, [String? title]) {3 if (title != null) {4 print('Hello $title $name');5 } else {6 print('Hello $name');7 }8}9 10// Default Values with Named Parameters11void buildBox({int width = 100, int height = 100}) {12 print('Box: ${width}x${height}');13}14 15void main() {16 greet('Alice'); // Hello Alice17 greet('Bob', 'Dr.'); // Hello Dr. Bob18 19 buildBox(); // Box: 100x100 (Defaults)20 buildBox(width: 50); // Box: 50x10021}HintDefault values (= value) are cleaner than handling null manually inside the function.
Loot collected
Key takeaways- Functions prevent code duplication and make apps easier to maintain.
- Use
voidif the function relies on side effects (like printing) and returns nothing. - Specify types for both parameters and return values for safety.
- Use Named Parameters (
{}) for clearer, more flexible function calls.
Side quests
Practice exercises
Exercise 1: Simple Function
Write a function greet that takes a name and prints "Welcome, [Name]".
Reveal solutionHide solution
1void greet(String name) { print('Welcome, $name'); }Exercise 2: Math Function
Write a function multiply that takes two numbers and returns the result.
Reveal solutionHide solution
1int multiply(int a, int b) { return a * b; }