Skip to main content

Introduction

Functions can return values to the calling code, making them more powerful and flexible. Instead of just performing actions, functions can compute and return results.

Basic Return Syntax

To return a value from a function, specify the return type and use the return keyword:
int operacion() {
  int valorUno = 10;
  int valorDos = 15;
  int suma = valorUno + valorDos;
  return suma;
}

Key Components

  • Return type: int - specifies what type of value the function returns
  • return statement: Returns the computed value back to the caller
  • Local variables: Variables defined inside the function are only accessible within it

Using Return Values

There are multiple ways to use the value returned by a function:

Direct Print

Print the returned value directly:
print(operacion());
// Output: 25

Store in Variable

Capture the return value in a variable for later use:
int resultado = operacion();
print('El Resultado de la Función es: $resultado');
// Output: El Resultado de la Función es: 25

String Interpolation

Embed the function call directly in a string:
print('El Resultado de la Función es: ${operacion()}');
// Output: El Resultado de la Función es: 25

Complete Example

int operacion(){
  int valorUno = 10;
  int valorDos = 15;
  int suma = valorUno + valorDos;
  return suma;
}

void main() {
  //Una forma de uso con Retorno
  print(operacion());

  //Otra forma es:
  int resultado = operacion();
  print('El Resultado de la Función es: $resultado');

  //Otra más
  print('El Resultado de la Función es: ${operacion()}');
}

Common Return Types

int

Returns integer numbers
int sumar(int a, int b) => a + b;

double

Returns decimal numbers
double dividir(int a, int b) => a / b;

String

Returns text values
String saludar() => 'Hola';

bool

Returns true or false
bool esMayor(int a, int b) => a > b;

Return Statement Rules

  • A function with a return type must return a value of that type
  • The return statement immediately exits the function
  • Code after a return statement won’t be executed
  • Functions with non-void return types must have a return statement in all code paths

Multiple Return Points

Functions can have multiple return statements based on conditions:
String obtenerCalificacion(int puntaje) {
  if (puntaje >= 90) {
    return 'A';
  } else if (puntaje >= 80) {
    return 'B';
  } else {
    return 'C';
  }
}
When storing return values in variables, make sure the variable type matches the function’s return type, or use var to let Dart infer the type.

Best Practices

  • Always specify the correct return type
  • Use meaningful variable names for stored return values
  • Return early to avoid deep nesting
  • Keep return logic simple and clear

Build docs developers (and LLMs) love