Creating lists
- Dart course
- Beginner
- Lesson 53/116
- 4 min
Learn to create Lists with [].
Creating lists
In Dart you use a List to hold several values in order. A List is written with comma-separated values inside square brackets: [1, 2, 3]. An empty List is [].
To assign a List to a variable you use var or an explicit type: var numbers = [1, 2, 3]; or List<int> numbers = [1, 2, 3];. The <int> type parameter says the list holds int elements. Dart usually infers the type itself.
Type parameter
A List states what element type it holds with a type parameter: List<int> for integers, List<String> for strings, List<double> for floating-point. The type parameter goes inside angle brackets.
When you declare with var Dart infers the type from the values: for var numbers = [1, 2, 3]; the type of numbers is List<int>. For an empty list a type hint is needed: var empty = <int>[]; or List<int> empty = [];. Otherwise the type stays ambiguous.
Practice Declare and print a List
Declare a List with var numbers = [1, 2, 3];. Then print it with print(numbers);. The output on a single line must be [1, 2, 3].
Starter code
// Declare numbers and print itSample solution
var numbers = [1, 2, 3];
print(numbers);Expected output
[1, 2, 3]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which one is a valid List literal?
?- <1, 2, 3>
- (1, 2, 3)
- {1, 2, 3}
- [1, 2, 3] Correct answer
Explanation: Comma-separated values inside square brackets form a List.
2 Complete the List declaration
var numbers = ____;
print(numbers);
var numbers = [1, 2, 3];
print(numbers);
Explanation: [1, 2, 3] is a three-element int list.
3 Match each part to its job
| Term | Meaning |
|---|---|
[1, 2, 3] |
Three-element list |
[] |
Empty list |
List<int> |
Type parameter |
var |
Type inference |