Dart Functions Part 2

Marc Kirk
2 min readMar 27, 2020

--

This tutorial extends our coverage of functions and explores how Dart functions are first-class objects.

Everything is an Object

Remember how I said everything in Dart is an object. This definition extends to functions as well. Functions are first-class objects. We can pass our functions as arguments to other functions and even assign functions to variables. This flexibility is a very powerful language feature I’m certain you will love.

1.   void main(){

2. var listOfStrings = ["functions", 'are', 'objects'];

3. listOfStrings.forEach(saySomething);
}
void saySomething(String element) {
print(element);
}
  1. Entry-point to our app void main()
  2. Here we create a list of String objects inside the variable listOfStrings
  3. For each item within listOfStringssaySomething is called and the item is passed to saySomething as an argument. In more concrete terms, this is what happens:

"functions" is passed to saySomething and saySomething prints functions.

"are" is passed to saySomthing and saySomething prints are.

Finally, "objects" is passed to saySomething and saySomething prints objects.

The net effect of passing the function saySomething to theforEach function multiple times can be observed below:

Assigning a Function to a Variable

void main(){

1. var makeTextBig = (String string) => print(string);

2. makeTextBig('make me big'.toUpperCase());
}
  1. We assign an anonymous function to the variablemakeTextBig. This anonymous function prints a string using shorthand function syntax =>. Anonymous functions are covered below.
  2. We invoke the function through the variable by calling the variable like we would a function and passing it a String argument. See output below:

Note how the variable makeTextBig is self-documenting. There is no confusion about what this variable does. It makes text — BIG. Having well named variables improves the readability of your code and reduces confusion. Furthermore, it helps declutter your codebase, because you no longer need to comment or annotate your code. Trust me on this one. Everybody who reads your code will be eternally greatful for your dedication to code quality.

Anonymous Functions

Still editing…

Help me help others by clicking on that clap button and leave a response.

--

--