You have used em' but you wanna know how it works.
A brief introduction to Closures in Dart ๐
A thread ๐งต
So, how do you define the onTap callback for GestureDetector?
Something like this right ๐๐ป
So, what is the datatype of the data member onTap?
It is ----> void Function()
But, if you open the code for GestureDetector, onTap will be of type "GestureTapCallback", which inturn is an alias for : void Function()
But, how does this work in Dart ??
How are we storing a function in a variable like that ??
It's simple, we use the concept of Lexical Closures, aka Closures.
Closures are also known as first-class functions.
The basic idea is that a function is also a value that can be passed around to other functions as a parameter.
Closures can be saved to a variable and used as parameters for other functions.
The most important usage of closures is for defining callbacks.
๐๐ ๐ฎ๐บ๐ฝ๐น๐ฒ: onTap in GestureDetector, onPressed in ElevatedButton, and so on.
The easiest and most maintainable way to work with closures is with the typedef keyword.
We define an alias for a function as follows:
Note: Function is the superclass of all the function types in dart.
Now, we can use this alias in a function like below:
So, how do we call this function calculateArea ??
We use the code below :
Here, we are passing an anonymous function as a parameter , and this function returns the value 10.
Now, this function is used twice to return the value 10, inside the function calculateArea.
So, this is how closures work in Dart. But wait, now lets see GestureDetector.
If you open the definition of the onTap attribute, you will see something like the one below ๐
If you open the definition for GestureTapCallBack? , you will see something like this ๐๐ป
Well, now it clears everything right. Now, we know how the onTap callback of GestureDetector works when we pass a callback.
But, how it internally works is out of the scope of this thread ๐
Hope you got a fair idea about Closures. If you liked it don't forget to like and retweet the first tweet !
Follow @GopinathanAswin for more threads like this. I will share more as I learn new things in the world of Dart and Flutter.
โข โข โข
Missing some Tweet in this thread? You can try to
force a refresh