Different ways to remove items from a dart list

How to remove items from a dart list:

Dart list provides a couple of methods to remove items from a list. In this post, I will show you how to use these methods with examples:

Remove a single item using remove():

For removing a single item from a dart list, remove is used. This method is defined as below:

bool remove(Object value)

It removes the first occurrence of value from the list. It returns true if the value is found in the list. Else, it returns false. If value is not found in the list, it does nothing.

For a fixed length list, it throws UnsupportedError.

Example:

void main() {
  List givenList = [1,2,3];
  givenList.remove(3);
  
  print(givenList);
}

It will print :

[1, 2]

Remove item at a specific index using removeAt:

removeAt is used to remove one item from a specific position. This method is defined as below:

dynamic removeAt(int index)

It removes the item from index index of the list. It changes the length of the list by 1 and updates the lengths of all other items.

The value of index must be valid, i.e. it can have a minimum value of 0 and maximum value of length - 1.

It returns the removed item.

For a fixed length list, it throws UnsupportedError. For invalid index, it throws RangeError.

Example:

void main() {
  List givenList = [1,2,3];
  givenList.removeAt(2);
  
  print(givenList);
}

It removes the item of index 3 and prints the below output:

[1, 2]

Remove the last item of a list using removeLast():

removeLast is defined as below:

dynamic removeLast()

This method works only with non empty list. It removes the last item of the list and returns the last item of the list.

For a fixed length list, it throws UnsupportedError.

void main() {
  List givenList = [1,2,3];
  givenList.removeLast();
  
  print(givenList);
}

It prints:

[1,2] 

Remove items at a range using removeRange:

removeRange is defined as below:

void removeRange(int start, int end)

It remove all items in the range of indices start (inclusive) and end(exclusive). The range should be valid. Even an empty range is also valid if start == end.

For fixed length list, it throws UnsupportedError. For invalid range, it throws RangeError.

Let’s take a look at the below example:

void main() {
  List givenList = [1,2,3,4,5,6,7,8,9];
  givenList.removeRange(2,5);
  
  print(givenList);
}

It will print:

[1, 2, 6, 7, 8, 9]

It removes the items from index 2 to index 4.

Remove items using a function removeWhere:

removeWhere takes a function and removes items based on that function:

void removeWhere(bool Function(dynamic) test)

It removes all items from a list that satisfy the passed function. The below example removes all even numbers from the list using removeWhere:

void main() {
  List givenList = [1,2,3,4,5,6,7,8,9];
  givenList.removeWhere((item) => item%2 == 0);
  
  print(givenList);
}

It prints:

[1, 3, 5, 7, 9]

You might also like: