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:

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:

Store in Variable

Capture the return value in a variable for later use:

String Interpolation

Embed the function call directly in a string:

Complete Example

Common Return Types

int

Returns integer numbers

double

Returns decimal numbers

String

Returns text values

bool

Returns true or false

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:
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