Dynamic invoke
- Dart course
- Advanced
- Lesson 21/83
- 5 min
Learn dynamic invoke with reflectable.
Dynamic method invocation
Reflection lets you take a method name (as a Symbol) and invoke it at runtime. In dart:mirrors, instanceMirror.invoke(symbol, args) does this.
An alternative without mirrors: Function.apply(fn, args). It dynamically calls a function with an argument list. Example: Function.apply(add, [3, 4]).
Another route: override noSuchMethod to catch unknown method calls. Combined with the dynamic type, flexible proxy classes can be written.
Function.apply example
Function.apply(fn, positionalArgs, namedArgs) calls fn with the given arguments. positionalArgs is a List, namedArgs a Map<Symbol, dynamic>.
Example: int add(int a, int b) => a + b; var r = Function.apply(add, [3, 4]);. The result is 7, just like add(3, 4).
Usage: selecting a method from a command-line argument, calling with parameter lists in test frameworks.
Practice Add with Function.apply
Define a top-level int add(int a, int b) => a + b; function. Inside main add var r = Function.apply(add, [3, 4]); and print(r);.
Starter code
void main() {
// define the add function (outside main)
// call add(3,4) via Function.apply; print it
}Sample solution
int add(int a, int b) => a + b;
void main() {
var r = Function.apply(add, [3, 4]);
print(r);
}Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Dynamic invocation routes
| Term | Meaning |
|---|---|
Function.apply |
Call function |
mirror.invoke |
Call method |
noSuchMethod |
Unknown call |
dynamic |
Drop type checks |
2 What does Function.apply do?
- Calls a function with an argument list Correct answer
- Renames a method
- Returns a Future
- Creates a class
Explanation: Function.apply calls fn with the given arguments.
3 Call the function
var r = ____(add, [3, 4]);
var r = Function.apply(add, [3, 4]);
Explanation: Function.apply(add, [3,4]) equals add(3,4).