What is a Function?
A function is a reusable block of code that performs a specific task. Functions help you avoid code repetition, improve readability, and make your code easier to test and maintain.
Syntax
returnType functionName(parameters) {
// function body
return value; // if returnType is not void
}
Return Types
int add(int a, int b) {
return a + b;
}
double circleArea(double radius) {
return 3.14159 * radius * radius;
}
String greet(String name) {
return 'Hello, $name!';
}
bool isEven(int n) {
return n % 2 == 0;
}
Void Functions
Functions that do not return a value use void as return type:
void printLine() {
print('─' * 30);
}
void showInfo(String name, int age) {
print('Name: $name, Age: $age');
}
Example
void main() {
// Call functions
int result = add(10, 20);
print('Sum: $result'); // 30
double area = circleArea(7.0);
print('Area: $${area.toStringAsFixed(2)}'); // 153.94
print(greet('Dart')); // Hello, Dart!
print(isEven(42)); // true
printLine();
showInfo('Alice', 25);
}
int add(int a, int b) => a + b;
double circleArea(double r) => 3.14159 * r * r;
String greet(String name) => 'Hello, $name!';
bool isEven(int n) => n % 2 == 0;
void printLine() => print('─' * 30);
void showInfo(String name, int age) =>
print('Name: $name, Age: $age');
Output:Sum: 30
Area: 153.94
Hello, Dart!
true
──────────────────────────────
Name: Alice, Age: 25
💪 Exercise
- Write a function
max(a, b) that returns the larger of two numbers.
- Write a function
isPrime(n) that returns true if n is a prime number.
- Write a function
celsiusToFahrenheit(c) that converts temperature.
🧠 Quiz
1. What return type does a function that returns nothing use?
- A) null
- B) empty
- C) void ✅
- D) none
2. Where can you define functions in Dart?
- A) Only inside main()
- B) Only in classes
- C) Top-level or inside classes ✅
- D) Only in separate files
Summary
Functions in Dart are defined with a return type, name, parameters, and body. Use void for functions that return nothing. Functions can be defined at the top level or inside classes. They eliminate repetition and make code reusable.