Types of List
There are two types of lists available in Dart. They are discussed as follows.
Fixed Length Lists
As the name suggests, these are lists with a fixed length, and the length cannot be varied at the runtime of the program. The syntax for creating a fixed-length list is as follows.
var list_name = new List.filled(list_size, null, growable:false)
The following is a sample program that shows the usage of a fixed-length list in Dart.
Code:
void main() {
var list_name = new List.filled(4, "", growable: false);
list_name[0] = "I";
list_name[1] = "am";
list_name[2] = "a";
list_name[3] = "Ninja";
print("The individual elements of the list:");
for(int i = 0; i < list_name.length; i++){
print("Index ${i+1}: " + list_name[i]);
}
print("The entire list is:");
print(list_name);
}
Output:
The individual elements of the list:
Index 1: I
Index 2: am
Index 3: a
Index 4: Ninja
The entire list is:
[I, am, a, Ninja]
Variable Length Lists
Sometimes it is required in the programs to create lists whose size can vary at the runtime of the program. Such lists are also available in Dart, like many other programming languages. These are also known as growable lists.
The following is a sample program that shows the usage of a variable-length list in Dart.
Code:
void main() {
var list_name = new List.filled(4, "", growable: true);
list_name[0] = "I";
list_name[1] = "am";
list_name[2] = "a";
list_name[3] = "Ninja";
print("The entire list before adding a new element:");
print(list_name);
list_name.add("ONE EXTRA ELEMENT");
print("The entire list after adding a new element:");
print(list_name);
}
Output:
The entire list before adding a new element:
[I, am, a, Ninja]
The entire list after adding a new element:
[I, am, a, Ninja, ONE EXTRA ELEMENT]
Frequently Asked Questions
-
Is it possible to create multi-dimensional lists in Dart?
Yes, it is possible to create multi-dimensional lists in Dart.
-
How can I insert multiple values to a list at a given index?
You can insert multiple values to a growable list at a specified index with the help of insertAll() method available in Dart.
-
What is the purpose of the replaceRange() method available in Dart?
The replaceRange() method is used to update the values of a list in a range that is specified in its input.
Conclusion
In this article, we have extensively discussed Lists in Dart and saw sample programs containing their implementation. You can also read the blog Dart Loops on the Coding Ninjas Website to learn about various types of loops available in the Dart programming language.
We hope that this blog has helped you enhance your knowledge regarding Dart Lists. If you want to learn more, check out our Android Development Course on the Coding Ninjas Website to learn everything you need to know about Android development. Do upvote our blog to help other ninjas grow. Happy Coding!