Multiple Return Values in Dart

Dart has built-in support for multiple return values, which is commonly used to return both result and error values from a function.

import 'dart:io';

// The List<int> in this function signature shows that
// the function returns a list of 2 integers.
List<int> vals() {
  return [3, 7];
}

void main() {
  // Here we use list destructuring to assign the
  // returned values to individual variables.
  var [a, b] = vals();
  stdout.writeln(a);
  stdout.writeln(b);

  // If you only want a subset of the returned values,
  // you can use the underscore (_) to ignore a value.
  var [_, c] = vals();
  stdout.writeln(c);
}

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

$ dart run multiple_return_values.dart
3
7
7

In Dart, we use a List to return multiple values from a function. We can then use list destructuring to assign these values to individual variables. If we only want a subset of the returned values, we can use the underscore (_) to ignore specific values, similar to the blank identifier in other languages.

This approach provides a clean and efficient way to handle multiple return values in Dart, making it easy to work with functions that need to return more than one piece of information.

Next, we’ll explore how to create functions that accept a variable number of arguments in Dart.