Closures in Flutter
Arpan Bhatia
8+ Years Experience, I am looking for New Opportunities, Contact at: 7906156955 || Sr. Developer @Team Computers Mobile Team || Android || Core Java || Kotlin || Flutter || Dart || Jetpack Components ||Jetpack Compose UI
A Closure is Function in Flutter that capture a value from its surroundings scope, even after scope exited. It is Function Object that can access variable in its lexical scope even it's sites outside of that scope is called a Closure.
Lexical Scope also known as 'static scope' is refers to the way a function and variable can accessed bases on there location in there code structure.
Let's take the Example of Closure for in depth Understanding:
Example 1 -
Function makeAdder(int addBy)
{
return (int i) => i+addby;
}
void main()
{
var add2 = makeAdder(3);
print(add2(2));
}
Output: 5
Closure Behavior:
When add2 is created by calling makeAdder(3), it capture addBy variable value i.e. 3 and give use result by adding 2+3 =5.
so the Function makeAdder(int addBy) is a Closure in this Example.
Example 2:
Function Counter
{
int count = 0;
return ()=> count+=1;
}
void main()
{
var myCounter = Counter();
print(myCounter());
print(myCounter());
print(myCounter());
}
Output :
1
2
3
In the above example the value picked by Global Scope from counter function so the old value of count variable got retained.
Conclusion:
Closures are a fundamental concept in programming that allow functions to capture and remember variables from their defining scope, even after that scope has exited. In Dart and Flutter, closures are extensively used for managing state, callbacks, and dynamic functionality.