On this page12 sections
Lecture 025: Functions & Methods
| Day | 10: Functions & Parameters |
| Lecture | 025 of 057 |
| Estimated video length | 12 min |
| Target | Dart 3.12 |
| Level | Beginner |
Copying the same ten lines into five places means fixing every bug five times. A function gives a block of code a name, so you write it once and use it anywhere. A method is a function that belongs to a class or object. You've been calling them since Lecture 004.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 006–024: variables, strings, collections, conditions and loops.
Learning Objectives
- Define and call a function
- Pass a value in with a parameter
- Send a value back with
return, and give the return type - Use
voidfor functions that return nothing - Write one-line functions with
=> - Tell functions and methods apart
1. Writing a Function
void greet() {
print('Hello!');
}
void main() {
greet(); // call it
greet(); // and again
}Output
Hello!
Hello!voidis the return type: this function gives nothing back.greetis the name.()holds the parameters (none here).{ ... }is the body, the code that runs on each call.
main itself is a function: the one Dart calls first.
2. Parameters: Values In
void greetUser(String name) {
print('Hello, $name!');
}
greetUser('Ayesha'); // Hello, Ayesha!name is a parameter: a variable that gets its value from the call. 'Ayesha' is the
argument, the value passed in. Lecture 026 covers parameters in depth.
3. return: Values Out
int square(int n) {
return n * n;
}
var result = square(6);
print(result); // 36
print(square(3) + square(4)); // 25The type before the name (int) says what the function gives back. return sends the value back
and ends the function immediately.
4. Arrow Functions
When the body is a single expression, use =>:
double areaOfCircle(double radius) => 3.14159 * radius * radius;
bool isEven(int n) => n % 2 == 0;
print(areaOfCircle(2).toStringAsFixed(2)); // 12.57
print(isEven(7)); // false=> expression means { return expression; }.
5. Functions vs Methods
A function stands on its own. A method belongs to a class and is called on an object with a dot:
// Standalone function
void greet() {
print('Hello!');
}
// Method within a class
class Person {
String name;
Person(this.name);
void introduce() {
print('My name is $name');
}
}
void main() {
greet(); // calling a function
var person = Person('John');
person.introduce(); // calling a method: My name is John
print('hello'.toUpperCase()); // a String method you already know
}Classes are covered on Day 11. Methods are written just like functions, but inside a class.
Code Examples
Example 1: A Weather Report
double celsiusToFahrenheit(double c) => c * 9 / 5 + 32;
String describeTemperature(double c) {
if (c >= 35) return 'Hot';
if (c >= 20) return 'Pleasant';
return 'Cold';
}
void printReport(String city, double c) {
var f = celsiusToFahrenheit(c);
print('$city: ${c}°C = ${f.toStringAsFixed(1)}°F (${describeTemperature(c)})');
}
void main() {
printReport('Karachi', 34);
printReport('Murree', 12);
printReport('Multan', 41);
}Output
Karachi: 34.0°C = 93.2°F (Pleasant)
Murree: 12.0°C = 53.6°F (Cold)
Multan: 41.0°C = 105.8°F (Hot)Each function does one small job, and printReport calls the other two. Change the formula in
one place, and every report uses it.
Common Beginner Mistakes
1. Forgetting return
int square(int n) {
n * n;
}Error: A non-null value must be returned since the return type 'int' doesn't allow null.Calculating n * n isn't enough: return n * n;.
2. Using the result of a void function
void greet() {
print('Hi');
}
var x = greet();
print(x);Error: This expression has type 'void' and can't be used.void means "nothing comes back". Return a value if you need one.
3. Writing the function inside main below the call
void main() {
print(square(4));
int square(int n) => n * n;
}Error: Local variable 'square' can't be referenced before it is declared.Put functions outside main, at the top level of the file. Then order doesn't matter.
4. Forgetting the brackets: greet; doesn't call the function. greet(); does.
Practice Questions
- What does
voidmean as a return type? - Write a function
double half(double x)that returns half ofx, using=>. - What's the difference between a parameter and an argument?
- What happens to the lines after
returnin a function? - Is
'hi'.toUpperCase()a function call or a method call?
Practice Answers
- The function doesn't return a value.
double half(double x) => x / 2;- The parameter is the variable in the definition (
n); the argument is the value in the call (6). - They don't run.
returnends the function. - A method call.
toUpperCasebelongs toString.
Key Takeaways
- A function is a named, reusable block:
returnType name(params) { body }. - Call it with
name(arguments). returnsends a value back and ends the function;voidmeans nothing comes back.=> expressionis a one-line function body.- A method is a function that belongs to a class:
object.method().