Functions as First Class Objects in Dart | Functions as Parameter | return a functions

Functions as First Class Objects in Dart | Functions as Parameter | return a functions

ยท

2 min read

  • 1. Functions as First-Class Objects:

    In Dart, functions are first-class objects, which means they can be:

    • Assigned to variables.

    • Passed as arguments to other functions.

    • Returned as values from other functions.

Example: Assigning a function to a variable:

    void main() {
        // Assigning a function to a variable
        Function greet = () {
            print('Hello, Dart!');
        };

        // Calling the function using the variable
        greet(); // Output: Hello, Dart!
    }

2. Functions as Parameters:

Dart allows you to pass functions as parameters to other functions, enabling you to customize behavior dynamically.

Example: Passing a function as a parameter:

    void say(String message, Function customGreeting) {
        print(message);
        customGreeting();
    }

    void main() {
        // Passing a function as a parameter
        say('Hi there!', () {
            print('Custom Greeting!');
        });
    }

3. Returning a Function:

You can return functions from other functions in Dart, allowing you to create functions dynamically.

Example: Returning a function:

    Function multiplyBy(int factor) {
        return (int number) => number * factor;
    }

    void main() {
        // Returning a function
        var multiplyByTwo = multiplyBy(2);
        print(multiplyByTwo(5)); // Output: 10
    }

In this last example, multiplyBy is a function that takes an integer factor and returns another function that multiplies a given number by that factor. The returned function (multiplyByTwo) is then used to multiply 5 by 2, resulting in 10.

These examples illustrate the versatility and power of treating functions as first-class objects in Dart, enabling more flexible and expressive code.

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!

ย