Functions in dart

Let’s dive into learning functions in Dart! I’ll break it down into simple topics and sub-topics, explain everything in easy words, and give you examples you can play with. Dart is a fun programming language used for apps (like Flutter), and functions are like little helpers that do specific tasks. Ready? Let’s go!
1. What is a Function?
A function is a block of code that does something specific. You can call it whenever you need that task done, like reusing a recipe instead of cooking from scratch every time.
Example:
dart
void sayHello() {
print("Hello, world!");
}
void main() {
sayHello(); // Calls the function, prints "Hello, world!"
}
Here, sayHello is a function that prints a message. void means it doesn’t return anything, and main is where the program starts.
2. Basic Parts of a Function
Let’s break down how to build a function:
a. Return Type
This tells Dart what kind of value the function gives back (like int, String, or void for nothing).
Example: int means it returns a number.
b. Function Name
- A name you give your function, like addNumbers. Use clear names so you know what it does.
c. Parameters (Optional)
- These are inputs you give the function to work with, like ingredients for a recipe.
d. Body
- The code inside {} that does the work.
Example:
dart
int add(int a, int b) {
return a + b; // Returns the sum
}
void main() {
print(add(3, 4)); // Prints 7
}
int is the return type.
add is the name.
(int a, int b) are parameters.
return a + b is the body.
3. Types of Functions
Functions come in different flavors. Let’s explore them!
a. Functions Without Parameters
- No inputs needed.
dart
void greet() {
print("Hi there!");
}
void main() {
greet(); // Prints "Hi there!"
}
b. Functions With Parameters
- Takes inputs to do something.
dart
void sayName(String name) {
print("Hello, $name!");
}
void main() {
sayName("Alice"); // Prints "Hello, Alice!"
}
c. Functions With Return Values
- Gives something back after finishing.
dart
double multiply(double x, double y) {
return x * y;
}
void main() {
print(multiply(2.5, 3)); // Prints 7.5
}
d. Functions Without Return (Void)
- Just does something, no value returned.
dart
void showMessage() {
print("This is a message.");
}
void main() {
showMessage(); // Prints "This is a message."
}
4. Parameters in Detail
Parameters make functions flexible. Here’s how they work:
a. Required Parameters
- You must provide these when calling the function.
dart
void addNumbers(int a, int b) {
print(a + b);
}
void main() {
addNumbers(5, 10); // Prints 15
}
b. Optional Positional Parameters
- Wrap them in []. You can skip them if you want.
dart
void describePerson(String name, [int? age]) {
if (age != null) {
print("$name is $age years old.");
} else {
print("Name: $name");
}
}
void main() {
describePerson("Bob"); // Prints "Name: Bob"
describePerson("Bob", 25); // Prints "Bob is 25 years old."
}
- ? means age can be null (nothing).
c. Optional Named Parameters
- Wrap them in {}. You name them when calling the function.
dart
void introduce(String name, {String? hobby, int? age}) {
print("I am $name.");
if (hobby != null) print("I like $hobby.");
if (age != null) print("I am $age.");
}
void main() {
introduce("Charlie", hobby: "gaming", age: 20);
// Prints:
// I am Charlie.
// I like gaming.
// I am 20.
}
d. Default Parameter Values
- Give parameters a default value if nothing is provided.
dart
void greetUser(String name, {String greeting = "Hello"}) {
print("$greeting, $name!");
}
void main() {
greetUser("Dana"); // Prints "Hello, Dana!"
greetUser("Dana", greeting: "Hi"); // Prints "Hi, Dana!"
}
5. Anonymous Functions (No Name)
Sometimes you don’t need to name a function—just use it once.
Example:
dart
void main() {
var numbers = [1, 2, 3];
numbers.forEach((number) {
print(number * 2); // Prints 2, 4, 6
});
}
- (number) { ... } is an anonymous function that doubles each number.
6. Arrow Functions (Short Syntax)
For simple one-line functions, use => instead of {}.
Example:
dart
int square(int x) => x * x;
void main() {
print(square(4)); // Prints 16
}
- \=> x x is a shortcut for return x x;.
7. Function as a Variable
You can store a function in a variable and use it later.
Example:
dart
void sayHi() {
print("Hi!");
}
void main() {
var myFunction = sayHi; // Store function in a variable
myFunction(); // Prints "Hi!"
}
8. Higher-Order Functions
Functions can take other functions as parameters or return them.
Example:
dart
void applyOperation(int a, int b, Function operation) {
print(operation(a, b));
}
int add(int x, int y) => x + y;
void main() {
applyOperation(5, 3, add); // Prints 8
}
- applyOperation uses the add function as an argument.
9. Recursion
A function can call itself to solve a problem, like counting down.
Example:
dart
void countdown(int n) {
if (n <= 0) {
print("Done!");
} else {
print(n);
countdown(n - 1);
}
}
void main() {
countdown(3); // Prints 3, 2, 1, Done!
}
10. Practical Example: Putting It Together
Let’s make a mini-program with different function types.
dart
// Simple function with return
double calculateArea(double width, double height) {
return width * height;
}
// Function with optional named parameters
void printDetails(String item, {int? quantity, double? price = 0.0}) {
print("Item: $item");
if (quantity != null) print("Quantity: $quantity");
if (price != null) print("Price: $price");
}
// Arrow function
String getFullName(String first, String last) => "$first $last";
void main() {
// Using the functions
print("Area: ${calculateArea(5, 3)}"); // Prints "Area: 15"
printDetails("Laptop", quantity: 2, price: 999.99);
// Prints:
// Item: Laptop
// Quantity: 2
// Price: 999.99
print(getFullName("John", "Doe")); // Prints "John Doe"
}
Tips to Remember
Use void if your function doesn’t return anything.
Add ? to types (like int?) if they can be null.
Keep function names descriptive (e.g., calculateTax not ct).
Test your functions in DartPad (online Dart editor) to see how they work!
That’s it! You’ve learned the basics of functions in Dart—how to create them, add parameters, return values, and even make them fancy with recursion or arrow syntax. Want to dive deeper into any part or try a specific example? Let me know!
Subscribe to my newsletter
Read articles from Singaraju Saiteja directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Singaraju Saiteja
Singaraju Saiteja
I am an aspiring mobile developer, with current skill being in flutter.