Dart List Common functions
In Dart, List
is a versatile and commonly used collection type that represents an ordered collection of items. Dart provides a variety of built-in functions (methods) to manipulate lists effectively. Here are some common functions you can use with lists in Dart:
1. Creation and Initialization
- Creating a List:
2. Adding Elements
add(): Adds an element to the end of the list.
addAll(): Adds multiple elements to the end of the list.
insert(): Inserts an element at a specified index.
insertAll(): Inserts multiple elements at a specified index.
3. Removing Elements
remove(): Removes the first occurrence of a specified element.
removeAt(): Removes the element at the specified index.
removeLast(): Removes the last element from the list.
removeRange(): Removes a range of elements from the list.
4. Accessing Elements
[] (Indexing): Accesses an element at a specified index.
first: Returns the first element of the list.
last: Returns the last element of the list.
length: Returns the number of elements in the list.
5. Checking Existence
contains(): Checks if the list contains a specific element.
isEmpty: Checks if the list is empty.
isNotEmpty: Checks if the list is not empty.
6. Iterating Through the List
forEach(): Executes a function for each element in the list.
map(): Applies a function to each element and returns a new list.
7. Sorting and Reversing
sort(): Sorts the list in ascending order.
reversed: Returns an iterable with the elements in reverse order.
8. Slicing and Modifying Lists
sublist(): Returns a new list containing a subset of the elements.
fillRange(): Replaces a range of elements in the list with a specified value.
Conclusion
Dart's List
collection provides a rich set of functions that allow you to create, manipulate, and access ordered collections efficiently. Understanding these common functions helps you work with lists effectively, making it easier to manage data in your applications. Whether you’re adding elements, removing them, or iterating through a list, Dart’s list methods simplify these tasks and enhance your coding experience.