Functions in Dart

Functions are central in Dart. We’ll learn about functions with a few different examples.

import 'dart:io';

// Here's a function that takes two `int`s and returns
// their sum as an `int`.
int plus(int a, int b) {
  // Dart allows implicit returns for single-expression functions
  return a + b;
}

// In Dart, you don't need to specify the type for parameters
// if they are of the same type as the function's return type
int plusPlus(int a, b, c) {
  return a + b + c;
}

void main() {
  // Call a function just as you'd expect, with
  // `name(args)`.
  var res = plus(1, 2);
  print('1+2 = $res');

  res = plusPlus(1, 2, 3);
  print('1+2+3 = $res');
}

To run the program, save it as functions.dart and use the dart command:

$ dart run functions.dart
1+2 = 3
1+2+3 = 6

In Dart, functions are first-class objects, which means they can be assigned to variables, passed as arguments to other functions, and returned from functions.

Dart supports both named and positional optional parameters, as well as default parameter values, which we’ll explore in future examples.

There are several other features to Dart functions. One is multiple return values, which we can achieve using tuples or custom objects.