Skip to main content

Introduction

Functions are reusable blocks of code that perform specific tasks. In Dart, functions help you organize your code and avoid repetition.

Basic Function Syntax

A basic function in Dart uses the void keyword when it doesn’t return a value:
void saludar() {
  print('Hola, Estoy usando Funciones Básicas en Dart');
}

Key Components

  • Return type: void indicates the function doesn’t return a value
  • Function name: saludar - should be descriptive of what the function does
  • Parentheses: () - contains parameters (empty in this case)
  • Body: Code block enclosed in curly braces {}

Calling Functions

To execute a function, simply use its name followed by parentheses:
void main() {
  // Call the function once
  saludar();
  
  // Call the function multiple times in a loop
  for (var i = 0; i < 10; i++) {
    saludar();
  }
}

Multiple Functions

You can define multiple functions in your program:
void saludar() {
  print('Hola, Estoy usando Funciones Básicas en Dart');
}

void imprimirBienvenida() {
  print('Bienvenido a el uso de Funciones Básicas');
}

void main() {
  saludar();
  imprimirBienvenida();
}
Functions must be defined before they are called, or they can be called from within the main() function regardless of where they’re defined in the file.

Complete Example

// Función SIN retorno
void saludar() {
  print('Hola, Estoy usando Funciones Básicas en Dart');
}

void imprimirBienvenida(){
  print('Bienvenido a el uso de Funciones Básicas');
}

void main() {
  // Llama función sin retorno
  saludar();          

  for (var i = 0; i < 10; i++) {
    saludar();
  }

  imprimirBienvenida();
}

Benefits of Functions

Code Reusability

Write once, use multiple times throughout your program

Better Organization

Group related code together for easier maintenance

Improved Readability

Make code more understandable with descriptive function names

Easier Testing

Test individual functions independently

Best Practices

  • Use descriptive names that clearly indicate what the function does
  • Keep functions focused on a single task
  • Use void for functions that don’t need to return a value
Avoid creating functions that are too long or do too many things. If a function becomes complex, consider breaking it into smaller functions.

Build docs developers (and LLMs) love