Get an introduction to the basics of the Dart programming language, used for development with the Flutter SDK for mobile, web and beyond.
By Jonathan Sande.
Dart supports first-class functions, meaning that it treats functions like any other data type. You can assign them to variables, pass them as arguments and return them from other functions.
To pass these functions around as values, omit the function name and return type. Since there’s no name, this type of function is called an anonymous function.
You can assign an anonymous function to a variable named onPressed, like so:
final onPressed = () {
print('button pressed');
};
onPressed has a value of type Function. The empty parentheses indicate the function has no parameters. Like regular functions, the code inside the curly brackets is the function body.
To execute the code within the function body, call the variable name as if it were the name of the function:
onPressed(); // button pressed
You can simplify functions whose body only contains a single line by using arrow syntax. To do this, remove the curly brackets and add a fat arrow =>.
Here’s a comparison of the anonymous function above and a refactored version:
You’ll often see anonymous functions in Flutter, like those above, passed around as callbacks for UI events. This lets you specify the code that runs when a user does something, like pressing a button.
Another common place where you’ll see anonymous functions is with collections. You can give a collection an anonymous function that will perform some task on each element of the collection. For example:
Define a list of drinks that have lowercase letters.
.map takes all the list values and returns a new collection with them.
An anonymous function is passed as a parameter. In that anonymous function, you have a drink argument that represents each element of the list.
The body of the anonymous function converts each element to uppercase and returns the value. Since the original list is a list of strings, drink also has type String.
Using an anonymous function and combining it with .map is a convenient way to transform one collection into another.
Note: Don’t confuse the .map method with the Map type.
Run the code to see the resulting collection.
Congratulations, you’ve finished the tutorial. You should now have a better understanding of the Dart code you see when learning how to build Flutter apps!
Where to Go From Here?
You can download the code examples using the Download Materials button at the top or bottom of this tutorial.
We hope you enjoyed this brief introduction to Dart basics. If you have any questions or comments, please join the forum discussion below.
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.