List in Dart: Start off with Useful Examples
A list in Dart is an ordered collection of elements. It can contain various data types and dynamically adjusts its size.
One of the coolest things about lists in Dart is their indices; we can use indices to access the elements in the list.
You can access elements by index, add, remove, and iterate through them. Lists also support common operations such as mapping, filtering, and sorting.
How to create a list in Dart?
Let’s create a dog breed list, including less popular breeds like Akita inu, Rajapalayam, and St. bernard.
List<String> dogs = [
"St. bernard",
"Pug",
"Akita inu",
"Rajapalayam",
"Chow chow",
"Beagle"
];
Program Example:
void main() {
List<String> dogs = [
"St. bernard",
"Pug",
"Akita inu",
"Rajapalayam",
"Chow chow",
"Beagle"
];
print(dogs);
}
Output
[St. bernard, Pug, Akita inu, Rajapalayam, Chow chow, Beagle]
Adding Elements
Let’s add an element at the end of the list.
dogs.add('Bulldog');
void main() {
List<String> dogs = [
"St. bernard",
"Pug",
"Akita inu",
"Rajapalayam",
"Chow chow",
"Beagle"
];
print(dogs);
// adding a new dog breed
dogs.add('Bulldog');
print(dogs);
}
[St. bernard, Pug, Akita inu, Rajapalayam, Chow chow, Beagle]
[St. bernard, Pug, Akita inu, Rajapalayam, Chow chow, Beagle, Bulldog]
Access the first element
String firstElement = dogs[0];
print(firstElement); // prints St.bernard
Insert at a specific index (location)
// Inserts at index 2
dogs.insert(2, 'Poodle');
How to add multiple elements?
//adding multiple elements
dogs.addAll(['Alaskan Malamute', 'French Bulldog']);
Iterating through a List (for loop)
for(var item in dogs)
{
print(item);
}
St. bernard
Pug
Poodle
Akita inu
Rajapalayam
Chow chow
Beagle
Bulldog
Alaskan Malamute
French Bulldog
Read more about loops in Dart
Using forEach
// forEach
dogs.forEach((dog){
print('Dog breed: $dog');
});
List length:
//finding length
var length = dogs.length;
print(length);
Checking List Contents
bool containsPug = dogs.contains('Pug');
print(containsPug);
Integer type
List<int> numbers = [1,45,67,9,11,10];
Mapping and Transformation in Dart with List
List<int> numbers = [1,45,67,9,11,10];
List<int> doubledNumbers = numbers.map((num) => num * 3).toList();
print(doubledNumbers);
Output
[3, 135, 201, 27, 33, 30]
Filtering elements in a List
Find odd numbers in a list:
List<int> oddNumbers = numbers.where((num) => num.isOdd).toList();
print("Odd numbers :$oddNumbers");
Odd numbers :[1, 45, 67, 9, 11]
Clear a List
//Clear a list
numbers.clear();
Removing Elements
// Removing elements
numbers.remove(11); //removes the first occurrence of 11
numbers.removeAt(1); //removes element at index 1
numbers.removeLast(); //removes the last element
Dart List to JSON String
To convert a Dart List to a JSON String, you can use the ‘json.encode’ method from the dart:convert library.
import 'dart:convert';
void main()
{
List<Map<String, dynamic>> names =[
{'name':'Jack', 'age': 45},
{'name':'Nikki', 'age': 65},
{'name':'Jocu', 'age':15},
];
//Convert List to JSON String
String jsonString = json.encode(names);
// display JSON string
print(jsonString);
}
[{"name":"Jack","age":45},{"name":"Nikki","age":65},{"name":"Jocu","age":15}]
Map vs List
Maps and Lists are collections used to store and manage data, they have fundamental differences in terms of structure and usage.
List
- An ordered collection of elements.
- Accessed by index (position in the list).
- Elements are stored sequentially, and their positions are determined by their indices.
- Commonly used when the order of elements matters, and quick access by position is required.
Map
- An unordered collection of key-value pairs.
- Accessed by key.
- Elements are stored with an associated key, and retrieval is based on the key.
- Ideal for scenarios where each element has a unique identifier (key), and quick access based on that identifier is needed.
In conclusion, lists and maps in Dart serve different purposes in managing collections of data. Lists are ordered collections accessed by index, suitable when the order of elements matters.