MOCKSTACKS
EN
Questions And Answers

More Tutorials









Dart Function scoping


Dart functions may also be declared anonymously or nested. For example, to create a nestedfunction, just open a new function block within an existing function block

void outerFunction() {
 bool innerFunction() {
 /// Does stuff
 }
}

The function innerFunction may now be used inside, and only inside, outerFunction. No other other functions has access to it.

Functions in Dart may also be declared anonymously, which is commonly used as function arguments. A common example is the sort method of List object. This method takes an optional argument with the following signature:

int compare(E a, E b)

The documentation states that the function must return 0 if the a and b are equal. It returns -1 if a <
b and 1 if a > b.
Knowing this, we can sort a list of integers using an anonymous function.

List<int> numbers = [4,1,3,5,7];
numbers.sort((int a, int b) {
 if(a == b) {
 return 0;
 } else if (a < b) {
 return -1;
 } else {
 return 1;
 }
});

Anonymous function may also be bound to identifiers like so:

Function intSorter = (int a, int b) {
 if(a == b) {
 return 0;
 } else if (a < b) {
 return -1;
 } else {
 return 1;
 }
}

and used as an ordinary variable.

numbers.sort(intSorter);


Conclusion

In this page (written and validated by ) you learned about Dart Function scoping . What's Next? If you are interested in completing Dart tutorial, your next topic will be learning about: Dart Using libraries.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.