Variadic parameters

suggest change

Many languages let a function accept any number of arguments: ...args in JavaScript, *args in Python, params in C#, vararg in Kotlin.

Dart has no variadic parameters. A function declares exactly which positional and named parameters it accepts and the compiler checks each call against that signature.

In practice that isn't much of a limitation because Dart offers several idioms that cover the same use cases:

The examples were run with Dart 3.13.

Taking a list

The idiomatic replacement for f(1, 2, 3) is f([1, 2, 3]). The parameter is an ordinary typed List or, more flexibly, an Iterable:

num sum(Iterable<num> values) {
  num total = 0;
  for (final v in values) {
    total += v;
  }
  return total;
}

T largest<T extends Comparable<Object>>(Iterable<T> items) {
  if (items.isEmpty) throw ArgumentError('items must not be empty');
  var best = items.first;
  for (final item in items.skip(1)) {
    if (item.compareTo(best) > 0) best = item;
  }
  return best;
}

void main() {
  print(sum([1, 2, 3]));
  print(sum([1.5, 2.5]));
  print(sum([]));
  print(sum({4, 5, 6}));
  print(sum([for (var i = 1; i <= 100; i++) i]));
  print(largest(['pear', 'apple', 'zucchini', 'fig']));
  print(largest([3, 17, 5]));
}

Output:

6
4.0
0
15
5050
zucchini
17

Compared to real varargs this costs only two brackets at the call site and has some advantages:

The standard library uses this style everywhere: Future.wait(futures), Object.hashAll(values), StringBuffer.writeAll(objects), List.addAll(iterable), Stream.fromIterable(...).

Note the bound Comparable<Object> in largest. int implements Comparable<num>, not Comparable<int>, so the more natural-looking T extends Comparable<T> infers T as num for [3, 17, 5] and can fail at runtime when combined with callbacks typed for int.

Optional positional parameters

When a function needs "one to a few" arguments, list them as optional positional parameters in square brackets. Each one is either nullable or has a default value:

String join3(String a, [String? b, String? c]) {
  final parts = [a, ?b, ?c];
  return parts.join(', ');
}

int add(int a, [int b = 0, int c = 0, int d = 0]) => a + b + c + d;

void main() {
  print(join3('x'));
  print(join3('x', 'y'));
  print(join3('x', 'y', 'z'));
  print(add(1));
  print(add(1, 2, 3, 4));
}

Output:

x
x, y
x, y, z
1
10

?b inside the list literal is a null-aware element (Dart 3.8+): it adds b only when it is not null.

The call sites look exactly like varargs calls, there is no allocation for the arguments, and every parameter is still statically typed. The obvious limit is that the maximum number of arguments is fixed by the declaration.

Telling "not passed" from null

With [String? b] you can't distinguish f('x') from f('x', null). If null is a legitimate value, use a private sentinel object as the default and compare with identical:

const Object _missing = _Missing();

class _Missing {
  const _Missing();
}

List<Object?> collect([
  Object? a = _missing,
  Object? b = _missing,
  Object? c = _missing,
  Object? d = _missing,
]) {
  return [a, b, c, d].where((x) => !identical(x, _missing)).toList();
}

void main() {
  print(collect());
  print(collect(1));
  print(collect(1, null));
  print(collect(1, null, 'three', [4]));
  print(Object.hash(1, 2) == Object.hash(1, 2));
  print(Object.hashAll([1, 2, 3]) == Object.hashAll([1, 2, 3]));
}

Output:

[]
[1]
[1, null]
[1, null, three, [4]]
true
true

The sentinel must be a const value because default values must be constants. Since _Missing is private, callers outside the library can't pass it by accident.

This is exactly how Object.hash is implemented in the SDK: it takes 2 required and 18 optional Object? parameters with a private sentinel default, so Object.hash(a, b, c) reads like a variadic call without allocating a list. For an unbounded number of values there is a companion Object.hashAll(Iterable). Providing both a fixed-arity version for the common case and a list version for the general case is a good pattern for your own APIs too.

Building arguments at the call site

Because the "varargs" are a collection literal, you get all the collection literal features for free: spread (... and ...?), collection if and collection for. A common shape is a function with a few fixed parameters followed by a list of "rest" arguments:

String format(String template, List<Object?> args) {
  var i = 0;
  return template.replaceAllMapped(RegExp(r'\{\}'), (m) {
    if (i >= args.length) {
      throw ArgumentError('not enough arguments for "$template"');
    }
    return '${args[i++]}';
  });
}

void log(String level, String message, [List<Object?> args = const []]) {
  print('[$level] ${format(message, args)}');
}

void main(List<String> argv) {
  final base = ['alice', 42];
  final extra = <Object?>[true];
  final verbose = !argv.contains('--quiet');

  log('INFO', 'server started');
  log('INFO', 'user {} has {} items', base);
  log('DEBUG', 'user {} has {} items, admin={}', [...base, ...extra]);
  log('DEBUG', 'values: {} {}', [1, if (verbose) 'verbose' else 'quiet']);
  try {
    log('WARN', '{} and {}', ['only one']);
  } on ArgumentError catch (e) {
    print(e.message);
  }
}

Output:

[INFO] server started
[INFO] user alice has 42 items
[DEBUG] user alice has 42 items, admin=true
[DEBUG] values: 1 verbose
not enough arguments for "{} and {}"

Things worth noting:

Variable named arguments

For a variable set of named options, accept a Map<String, Object?>. Combined with a list parameter this covers what Python's *args, **kwargs are typically used for:

String tag(String name, {Map<String, Object?> attrs = const {}, List<String> children = const []}) {
  final a = attrs.entries.map((e) => ' ${e.key}="${e.value}"').join();
  return '<$name$a>${children.join()}</$name>';
}

void main() {
  print(tag('br'));
  print(tag('a', attrs: {'href': '/home', 'class': 'nav'}, children: ['Home']));
  print(tag('ul', children: [
    for (final item in ['one', 'two']) tag('li', children: [item]),
  ]));
}

Output:

<br></br>
<a href="/home" class="nav">Home</a>
<ul><li>one</li><li>two</li></ul>

If the set of options is known in advance, prefer real named parameters (see Functions with named parameters) because they are type checked and auto-completed by the IDE. A map is for genuinely open-ended keys.

Heterogeneous arguments with records

A List<Object?> loses the types of its elements. When each "variadic" item is itself a small group of differently typed values, use a list of records:

// Records: a fixed but heterogeneous "bundle" of arguments.
String describe((String, int, bool) row) {
  final (name, age, active) = row;
  return '$name ($age) ${active ? 'active' : 'inactive'}';
}

// Pass many typed rows as a list of records.
void printTable(List<(String, int)> rows) {
  for (final (label, value) in rows) {
    print('${label.padRight(8)}${value.toString().padLeft(5)}');
  }
}

void main() {
  print(describe(('Ann', 31, true)));
  final row = ('Bob', 45, false);
  print(describe(row));
  printTable([('apples', 12), ('pears', 7), ('plums', 130)]);
}

Output:

Ann (31) active
Bob (45) inactive
apples     12
pears       7
plums     130

Every element of rows is checked to be a (String, int) at compile time, and the for loop destructures each record (see Destructuring).

Calling a function with a list of arguments: Function.apply

The reverse problem is when you have the arguments in a list at runtime and want to call a function that takes ordinary parameters, like f(...args) in JavaScript. Use Function.apply(function, positional, named). Named arguments are passed as a Map<Symbol, dynamic>:

int add3(int a, int b, int c) => a + b + c;

String greet(String name, {String greeting = 'Hello', bool shout = false}) {
  final s = '$greeting, $name!';
  return shout ? s.toUpperCase() : s;
}

void main() {
  final args = [1, 2, 3];
  print(Function.apply(add3, args));

  print(Function.apply(greet, ['Ann']));
  print(Function.apply(greet, ['Bob'], {#greeting: 'Hi', #shout: true}));

  try {
    Function.apply(add3, [1, 2]);
  } on NoSuchMethodError catch (e) {
    print('NoSuchMethodError: ${e.toString().split('\n').first}');
  }

  // The result is dynamic: type checks happen at run time.
  final dynamic r = Function.apply(add3, [10, 20, 30]);
  print('$r ${r.runtimeType}');
}

Output:

6
Hello, Ann!
HI, BOB!
NoSuchMethodError: NoSuchMethodError: Closure call with mismatched arguments: function 'add3'
60 int

Function.apply bypasses static checking: a wrong number or type of arguments is only detected when the call happens. It is also slower than a direct call. Use it for generic plumbing such as command dispatchers, test helpers or RPC layers, not in ordinary code.

Truly variadic calls with noSuchMethod

There is one way to make an object accept any call: override noSuchMethod and invoke the object through a dynamic reference. A call like obj(1, 2, 3) is a call to the call method; if the class doesn't define one, Dart invokes noSuchMethod with an Invocation describing the arguments:

typedef Handler = void Function(List<Object?> positional, Map<Symbol, Object?> named);

class VarArgs {
  final Handler _handler;
  VarArgs(this._handler);

  @override
  dynamic noSuchMethod(Invocation invocation) {
    if (invocation.memberName == #call) {
      return _handler(invocation.positionalArguments, invocation.namedArguments);
    }
    return super.noSuchMethod(invocation);
  }
}

void main() {
  final dynamic printAll = VarArgs((pos, named) {
    print('positional: $pos, named: $named');
  });

  printAll();
  printAll(1);
  printAll(1, 'two', 3.0);
  printAll('x', sep: ', ', end: '!');
}

Output:

positional: [], named: {}
positional: [1], named: {}
positional: [1, two, 3.0], named: {}
positional: [x], named: {Symbol("end"): !, Symbol("sep"): , }

Combined with Function.apply this lets you write generic wrappers that forward any arguments to any function, similar to Python decorators:

import 'dart:math';

/// Wraps any function so that each call is logged with its arguments.
class Logged {
  final String name;
  final Function target;
  Logged(this.name, this.target);

  @override
  dynamic noSuchMethod(Invocation inv) {
    if (inv.memberName != #call) return super.noSuchMethod(inv);
    final result =
        Function.apply(target, inv.positionalArguments, inv.namedArguments);
    print('$name${inv.positionalArguments} '
        '${inv.namedArguments.length} named -> $result');
    return result;
  }
}

String pad(String s, {int width = 8, String fill = '.'}) =>
    s.padLeft(width, fill);

void main() {
  final dynamic lmax = Logged('max', max);
  final dynamic lpad = Logged('pad', pad);
  lmax(3, 7);
  lpad('abc');
  lpad('abc', width: 5, fill: '*');
}

Output:

max[3, 7] 0 named -> 7
pad[abc] 0 named -> .....abc
pad[abc] 2 named -> **abc

This is a neat trick, but it has real costs:

Treat it as a tool for mocks, proxies and DSL experiments. Mocking libraries like mockito rely on the same noSuchMethod mechanism.

Pitfall: a list is one argument

Because "varargs" are just a list, passing a list inside a list literal nests it rather than spreading it:

void printEach(List<Object?> items) {
  print('${items.length} item(s): $items');
}

void main() {
  final names = ['a', 'b'];
  printEach(names);       // 2 items
  printEach([names]);     // 1 item: a nested list
  printEach([...names, 'c']);
  printEach(const []);
}

Output:

2 item(s): [a, b]
1 item(s): [[a, b]]
3 item(s): [a, b, c]
0 item(s): []

With a typed parameter such as List<String> the compiler catches the mistake. With List<Object?> or List<dynamic> it doesn't, which is another reason to give the "rest" parameter the most specific element type possible.

Which approach to use

Need Use
Any number of values of one type Iterable<T> / List<T> parameter
One to a handful of values optional positional parameters [a, b, c]
null is a valid value and "absent" must be detected private const sentinel default
Fast common case plus unbounded general case fixed-arity function plus ...All(Iterable) variant, like Object.hash / Object.hashAll
Spread existing collections into the call [...a, ...b, if (x) c] at the call site
Open-ended named options Map<String, Object?> named parameter
Groups of differently typed values List of records
Arguments only known at runtime Function.apply
Intercept arbitrary calls (proxies, mocks) noSuchMethod with a dynamic receiver

The first two rows cover almost all real code. Reach for Function.apply and noSuchMethod only when you are writing infrastructure that must handle functions whose signatures you don't know.

See also Functions, Generics and Reflection and introspection.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents