What is anonymous function in Flutter

When a function has no name, it is anonymous. Otherwise, we call it a named function. Most functions are named. Consider the top level function main(). It is a named function.

In Dart is everything is Object. As a result, a function is also an Object. That means every function has a base class for all function “Type”.

Now, in Flutter, we need both types of functions. The named function and the anonymous functions. However, most common of them is the “VoidCallback” which has no argument and returns no data.

In other words, it is void Function().

However, whether a function is named or anonymous, the question is why we need them in Flutter?

Firstly, we need functions for many reasons. A user may tap an image and a new page opens up. Or, a user types the username and password and presses a button to log in.

A function is a block that consists some instructions. As a result, a function may call one or more functions. That means more instructions are associated with one another.

There are endless possibilities.

Secondly, every button in Flutter comes with different types of void functions. Or, in other words, “VoidCallback”.

They are anonymous functions.

Let us see some simple examples of named functions and anonymous functions in Dart.

void main() {
  // named function
  void pressThreeDBuddy() {
    print('Pressing a 3D Buddy.');
  }
  // calling a function
  pressThreeDBuddy();
  // output: Pressing a 3D Buddy.
  
  // anonymous function
  Function anonymous;
  anonymous = () {
    print('Pressing anonymously.');
  };
  // calling an anonymous function
  anonymous();
  // output: Pressing anonymously.
}

First we declare a named function. Then we call the function. And it gives us an output.

In case of an anonymous functions, we can assign them to a variable. Once we assign the anonymous function to a Function variable, it becomes a named function.

And we can call them as a named function.

Subsequently, anonymous functions are also known as lambda or closure.

How do you define anonymous function?

An anonymous function is always associated with a variable whose data type is Function.

// anonymous function 
  Function anonymous;
  anonymous = () {
    print('Pressing anonymously.');
  };
  // calling an anonymous function
  anonymous();
  // output: Pressing anonymously.

In the above example, we have assigned an anonymous function to a variable “anonymous”. The variable “anonymous” has a data type – Function.

After that, when we call the anonymous function it acts as the named function.

// calling an anonymous function
  anonymous();

When should I use anonymous functions?

In Flutter, when we want to return another function, we use anonymous function.

It is lighter than any named function.

Moreover, we want an anonymous function when we know that we do not need to call it more.

May be once, or a limited number of times.

These are main reasons why Flutter uses the anonymous functions quite often.

Consider three images placed inside a Row Widget.

Anonymous function Example in Flutter
Anonymous function Example in Flutter

Each image represents a 3D Buddy. Let us name them. The first one is “Greedy”. The second one is “Confident”, and the third one is “Careless”.

We may wrap each Image Widget with the GestureDetector Widget.

body: Center(
        child: Row(
          children: [
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(18.0),
                child: GestureDetector(
                  onTap: () {
                    print('I am Greedy 3D Buddy.');
                  },
                  child: Image.asset('images/greedy.jpg'),
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(18.0),
                child: GestureDetector(
                  onTap: () {
                    print('I am Confident 3D Buddy');
                  },
                  child: Image.asset('images/confident.jpg'),
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(18.0),
                child: GestureDetector(
                  onTap: () {
                    print('I am Careless 3D Buddy.');
                  },
                  child: Image.asset('images/careless.jpg'),
                ),
              ),
            ),
          ],
        ),
      ),
...

Each GestureDetector Widget has a property “onTap” which expects a “VoidCallback” or an anonymous function.

As a result, when we click any image, it gives us an output on the terminal.

If we click the first image, the output is – I am Greedy 3D Buddy.

Certainly, we do not use anonymous functions this way in Flutter. A user is not supposed to watch the output on a terminal.

On the other hand, we can expect that when we click an image, it should start an animation. Or, the image is replaced by another image. Or, it navigates the user to another page.

In the coming section, we will discover what we can do with these anonymous functions.

And for this part, you will find the full code snippet in this GitHub repository.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

Courses at Educative

GitHub repository

Technical blog

Twitter

Comments

3 responses to “What is anonymous function in Flutter”

  1. […] onPressed property of the ElevatedButton returns an anonymous void function. […]

  2. […] sections we have learned a lot of new features in Flutter. That includes how to refactor code, anonymous functions, and moreover, the role of Stateful widget. We have also built a simple Photo App that changes when […]

  3. […] the previous section we have built a simple Photo App. We have also learned what is anonymous function in […]

Leave a Reply