Dart Functions
A function is a named block of code that does one job. A program calls the name to run that job.
Repeated lines without a function
Two greetings sit as two separate print lines in main. A new name means a new line written by hand.
void main() {
print('Hello Ana');
print('Hello Bo');
}One function called twice
greet holds one print line and main calls it twice. Each call runs the body again.
void greet() {
print('Hello');
}
void main() {
greet();
greet();
}A function with one parameter
The definition names one String parameter called name. Each call passes a different name into the same body.
void greet(String name) {
print('Hello $name');
}
void main() {
greet('Ana');
greet('Bo');
}A function with two parameters
add takes two int parameters and prints their sum. The two calls pass different pairs and get different sums.
void add(int a, int b) {
print(a + b);
}
void main() {
add(2, 3);
add(10, 5);
}Example
void showTotal(int price, int count) {
print(price * count);
}
void main() {
showTotal(3, 4);
showTotal(2, 5);
}Key points
- A function is a named block of code that does one job.
- A function definition sits above main in this course.
- Parameters are the named inputs inside the round brackets of a definition.
- Each parameter names a kind for the value it takes.
- A call writes the function name and one value for each parameter.
- void before a name marks a function that sends no value back.
In this example, showTotal takes a price and a count as its parameters. Its body prints the price times the count. The first call passes 3 and 4, so the print shows 12. The second call passes 2 and 5, so the print shows 10.
Note
main is a function too, and the program starts there.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What does void before a function name mark?