Dart Anonoymous Functions: Callback Functions

Vinit MepaniVinit Mepani
2 min read

Dart Anonymous Functions: Callback Functions

In Dart, anonymous functions play a crucial role in implementing callback functions. Callback functions are functions passed as arguments to other functions, and they get executed at a later time. This is a powerful concept, especially when dealing with asynchronous operations or events.

Example: Using Anonymous Functions as Callbacks:

void main() {
    // Simulating an asynchronous operation with a delay
    void fetchData(void Function(String) callback) {
        // Simulating a delay of 2 seconds
        Future.delayed(Duration(seconds: 2), () {
            // Data fetched after the delay
            String data = "Dart is awesome!";

            // Calling the callback function with the fetched data
            callback(data);
        });
    }

    // Using an anonymous function as a callback
    fetchData((result) {
        print("Fetched Data: $result");
    });

    print("Fetching data..."); // Printed immediately, before the data is fetched
}

In this example, the fetchData function takes a callback function as a parameter. Inside fetchData, we simulate an asynchronous operation using Future.delayed to represent fetching data after a delay. Once the data is ready, the callback function is executed with the fetched data.

The anonymous function (result) { print("Fetched Data: $result"); } is passed as a callback to fetchData. It gets executed when the data is ready, allowing us to handle the result.

Callbacks, along with anonymous functions, are powerful tools in Dart, particularly in scenarios where you need to manage asynchronous operations, events, or respond to certain conditions. They provide a flexible way to handle functionality that occurs at a later time in your program.

0
Subscribe to my newsletter

Read articles from Vinit Mepani directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vinit Mepani
Vinit Mepani

"Hello World, I'm Vinit Mepani, a coding virtuoso driven by passion, fueled by curiosity, and always poised to conquer challenges. Picture me as a digital explorer, navigating through the vast realms of code, forever in pursuit of innovation. In the enchanting kingdom of algorithms and syntax, I wield my keyboard as a magical wand, casting spells of logic and crafting solutions to digital enigmas. With each line of code, I embark on an odyssey of learning, embracing the ever-evolving landscape of technology. Eager to decode the secrets of the programming universe, I see challenges not as obstacles but as thrilling quests, opportunities to push boundaries and uncover new dimensions in the realm of possibilities. In this symphony of zeros and ones, I am Vinit Mepani, a coder by passion, an adventurer in the digital wilderness, and a seeker of knowledge in the enchanting world of code. Join me on this quest, and let's create digital wonders together!"