CodeBlanks Logo Icon CodeBlanks

Defining functions

Learn how to define and call a function.

Defining functions

In Dart a function is declared as returnType name(params) { ... }. When there is no value to return, write void. Example: void greet() { print('Hello'); }.

You call a function by its name followed by parentheses: greet();. When this line runs, the function body executes. Parentheses are required even when the function takes no parameters.

Functions group code: you write a task once and call it from many places. This reduces repetition and improves readability. Parameters and return values are detailed in the next lessons.

Calling and parentheses

To call a function you write its name followed by parentheses. When it takes no parameters, the parentheses stay empty: greet();. Without parentheses, greet; alone is a reference to the function, not a call.

This distinction matters later with first-class functions; you will see the details soon. For now: to run it, add the parentheses.

A call works as long as the definition appears before it. Dart must have seen the function definition by the time it is called. Calling other functions from main is the standard layout of a Dart program.

Practice Write and call greet

Define a greet function whose body calls print('Hello'). Add a greet() call inside main.

Starter code

main.dart
void main() {
  // define the greet function

  // call greet
}

Sample solution

main.dart
void greet() {
  print('Hello');
}

void main() {
  greet();
}

Expected output

Hello

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is written when there is no return value?

main.dart
void greet() { print('Hello'); }
  • int
  • var
  • void Correct answer
  • null

Explanation: void marks that there is no return value.

2 Match the function parts

Term Meaning
void No return
greet Function name
() No parameters
greet(); Call

3 Function definition

Question
void greet() {
  print(____);
}
void main() { greet(); }
Answer
void greet() {
  print('Hello');
}
void main() { greet(); }

Explanation: The string goes inside single quotes.

All lessons in Beginner