Dart Functions
Dart Functions
A function is a block of code that only runs when it is called.
You can pass data, known as parameters, into a function.
A function can also give data back as a result.
Functions let you write code once and use it many times.
Create a Function
To create (define) a function, write the return type, the name of the function, parentheses () and curly brackets {}:
void sayHello() {
print('Hello!');
}
voidis the return type, and it means that the function does not give back a valuesayHellois the name of the function- The code inside the curly brackets is the body of the function
Function names use lowerCamelCase, like variable names.
Call a Function
To call (run) a function, write its name followed by parentheses and a semicolon:
Result:
Hello!
A function can be called as many times as you want:
Example
void sayHello() {
print('Hello!');
}
void main() {
sayHello();
sayHello();
sayHello();
}
Try it Yourself »
Result:
Hello!
Hello!
Hello!
If you forget the parentheses, the function is not called.
The main() Function
You have used one function in every program so far: main().
main() is a special function, because Dart calls it for you when the program starts.
All other functions only run when your code calls them:
Example
void greet() {
print('Welcome!');
}
void unused() {
print('This line is never printed');
}
void main() {
print('Program starts');
greet();
print('Program ends');
}
Try it Yourself »
Result:
Program starts
Welcome!
Program ends
Top-Level Functions
A function that is written outside of any other function or class is called a top-level function.
main(), sayHello() and greet() above are all top-level functions.
The order does not matter, so you can call a top-level function that is written further down in the file:
Example
void main() {
printLine();
print('Menu');
printLine();
}
void printLine() {
print('----------');
}
Try it Yourself »
Result:
----------
Menu
----------
Return a Value
A function can give a value back to the code that called it.
Instead of void, you write the type of the value, and use the return keyword:
Example
int getMaxScore() {
return 100;
}
String getGreeting() {
return 'Good morning';
}
void main() {
int maxScore = getMaxScore();
print(maxScore);
print(getGreeting());
}
Try it Yourself »
Result:
100
Good morning
The function call is replaced by the value it returns, so you can store it in a variable or print it directly.
A function becomes more useful when you can give it data.
A small example, with a parameter called name:
Example
void greet(String name) {
print('Hello, $name!');
}
void main() {
greet('Tom');
greet('Anna');
}
Try it Yourself »
Result:
Hello, Tom!
Hello, Anna!
You will learn about parameters in the next chapter, Parameters, and more about return values in Return Values.