1

Could anyone please explain the difference between if I call the method doSomeAction in both the ways.

doSomeAction() {
        ...
}
 

   
  GestureDetector() {
    onTap: () {
      doSomeAction();
    }
  }

  GestureDetector() {
    onTap: doSomeAction;
  }

3 Answers3

1

The only difference is that you have one additional indirection.

Here, when a tap happens, a function is called that does nothing but call your function:

onTap: () { doSomeAction(); }

While this version directly calls your function. Without the empty redirection in the middle:

onTap: doSomeAction;

You only really need the first version, if your method signatures do not match and you have to do something about it. If you already have a method that has the exact signature required, and you want to do nothing but call it directly, you can just pass it as in version #2. Version #1 in that case is just a lot of unnecessary extra characters.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • What happens if I use onTap: doSomeAction() – Umakanth Pendyala Jul 01 '20 at 14:12
  • You will most likely get a compile error. That's not valid. It would only be valid if your method returned another method. – nvoigt Jul 01 '20 at 14:17
  • https://stackoverflow.com/questions/59497620/what-is-the-difference-between-calling-the-function-without-parentheses-and-with. Could you please take a look at that link and look at (peter Haddad's) reply. He talks about executing immediately... Could you please explain what he was trying to say – Umakanth Pendyala Jul 01 '20 at 14:24
  • He is trying to say that "onTap" expects a function reference. The name of a function to call at a later point in time. The name of a function is given without (), because if you add the () if would actually call the function instead of pass it's reference along. – nvoigt Jul 01 '20 at 14:27
1

Both of them are similar in functionality.

But, the main difference is that if you wrap your action inside an anonymous function, you could have more than 1 action. For example:

  GestureDetector() {
    onTap: () {
      // Action 1
      // Action 2
      // Action 3 and so on
    }
  }

On the other hand, if you directly assigned it, it will allow you to do one single action.

Hope it will help you.

hisam
  • 1,566
  • 1
  • 7
  • 21
0

when you write onTap: doSomeAction you actually don't call it - you just say that doSomeAction function will be called when the button is pressed.

Amit Kabra
  • 233
  • 1
  • 9