Junior
What are anonymous functions?
sobes.tech AI
Answer from AI
An anonymous function (or lambda expression) in Dart/Flutter is a function without a name. It can accept arguments and return a value, similar to regular functions, but is defined directly where it is used.
Main characteristics:
- Nameless: They do not have an identifier for calling by name.
- Inline definition: They are created and used immediately where needed.
- Closures: They can capture variables from the scope where they were defined.
Examples of usage:
- As parameters to other functions (e.g., callbacks).
- For short, one-time operations.
// Example of using an anonymous function as a callback for the forEach method
List<int> numbers = [1, 2, 3];
numbers.forEach((number) {
print(number * 2);
});
// Anonymous function assigned to a variable
var multiply = (int a, int b) {
return a * b;
};
print(multiply(5, 3));
Advantages:
- More concise code for simple operations.
- Allows passing behavior as an argument.
- Frequently used in functional programming.