AgentSkillsCN

various-ways-to-invoke-functions-in-dart

探索 Dart 函数调用的惊人灵活性,包括混合位置参数与命名参数、.call 运算符,以及通过 Function.apply 实现动态调用。

SKILL.md
--- frontmatter
name: various-ways-to-invoke-functions-in-dart
description: Discover the surprising flexibility of calling Dart functions, including mixed positional and named arguments, the `.call` operator, and dynamic invocation with `Function.apply`.
metadata:
  url: https://rodydavis.com/posts/dart/function-invoking
  last_modified: Tue, 03 Feb 2026 20:04:32 GMT

Various Ways to Invoke Functions in Dart

There are multiple ways to call a Function in Dart.

The examples below will assume the following function:

code
void myFunction(int a, int b, {int? c, int? d}) {
  print((a, b, c, d));
}

But recently I learned that you can call a functions positional arguments in any order mixed with the named arguments. 🤯

code
myFunction(1, 2, c: 3, d: 4);
myFunction(1, c: 3, d: 4, 2);
myFunction(c: 3, d: 4, 1, 2);
myFunction(c: 3, 1, 2, d: 4);

In addition you can use the .call operator to invoke the function if you have a reference to it:

code
myFunction.call(1, 2, c: 3, d: 4);

You can also use Function.apply to dynamically invoke a function with a reference but it should be noted that it will effect js dart complication size and performance:

code
Function.apply(myFunction, [1, 2], {#c: 3, #d: 4});

All of these methods print the following:

code
(1, 2, 3, 4)

Demo