Closures in Flutter

Closures in Flutter

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.


要查看或添加评论,请登录

Arpan Bhatia的更多文章

  • Higher Order Functions in Dart & Flutter:

    Higher Order Functions in Dart & Flutter:

    Higher Functions are the function that are used to make our code more concise, flexible and reusable. A higher order…

  • Extensions in Flutter

    Extensions in Flutter

    In Flutter extensions allowed to you to add some new functionality to existing class without modified their original…

  • Mixin in Dart:

    Mixin in Dart:

    As the name suggest Mixin is use to mix it with some thing .In Flutter Mixin is way to reuse a code into multiple class…

    1 条评论
  • Kotlin Flows and Channels

    Kotlin Flows and Channels

    In modern software development, asynchronous programming has become a crucial aspect of building responsive and…

    1 条评论
  • StateLess Widget in Flutter

    StateLess Widget in Flutter

    Stateless widget simply means the widget that will be return in this class will not contain any state and it will never…

社区洞察

其他会员也浏览了