Lists
7 min · Dart
Hold many values under one name, and reach for the one you want.
Enemy 1 of 5
What a List is
A List holds several values in order, and you get one by its position, starting at 0. This code makes a list of fruits and prints the first one. Press Run to see it.
Why this works
A List is Dart's ordered collection type, a single variable that holds several values in a fixed sequence, written inside square brackets: ['apple', 'banana', 'cherry']. Instead of juggling separate variables for each fruit, you keep them together as one list and access whichever one you need by its position.
Like every language in this course, Dart indexes lists starting at 0 rather than 1: the first element sits at index 0, the second at index 1, and so on. You retrieve an element with square brackets after the list's name: fruits[0] gives you 'apple'. Forgetting this and expecting fruits[1] to be the first element is an extremely common early mistake.
Because var infers a type, var fruits = ['apple', 'banana', 'cherry']; actually creates a List<String>, a list specifically typed to hold Strings. Dart will stop you at compile time if you try to add a number into a list Dart has inferred as a List<String>, which is a safety net some other dynamically-typed languages don't provide.
Rena
Your AI tutor. She walks you through each step.
Asking for help is part of coding. Rena reads your code and gives you a hint. She is free with an account: 20 hints a day.