How to remove items from a list in Dart

Last updated on November 23, 2020 A Goodman Loading... Post a comment

One of the most common tasks you encounter while working with a list in Dart is removing its items. Similar to various programming languages, Dart has some built-in functions that help us get this matter done quickly.

remove()

This method is used to remove the first occurrence of a value from a list. It returns true if that value was in the list, returns false otherwise.

Example:

final myList = ['a', 'b', 'c', 'd', 'e', 'f', 'd', 'b'];
void main(){
  myList.remove('b');
  print(myList); 
}

Output:

[a, c, d, e, f, d, b]

removeWhere()

This method is used to remove all items from a list that satisfy one or many conditions.

Example:

final List<Map<String, dynamic>> people = [
  {
    'name': 'John',
    'age': 30
  },
  {
    'name': 'Bob',
    'age': 50
  },
  {
    'name': 'Tom',
    'age': 14
  },
  {
    'name': 'Donald',
    'age': 3
  }
];

void main(){
  people.removeWhere((person) => person['age'] <= 18);
  print(people); 
}

Output:

[{name: John, age: 30}, {name: Bob, age: 50}]

removeAt()

This method is used to remove an item at position index from a list.

Example:

final List<Map<String, dynamic>> people = [
  {
    'name': 'John',
    'age': 30
  },
  {
    'name': 'Bob',
    'age': 50
  },
  {
    'name': 'Tom',
    'age': 14
  },
  {
    'name': 'Donald',
    'age': 3
  }
];

void main(){
  people.removeAt(2);
  print(people); 
}
  

Output:

[{name: John, age: 30}, {name: Bob, age: 50}, {name: Donald, age: 3}]

removeLast()

This methods pops and returns the last item of a list.

Example:

final List<Map<String, dynamic>> people = [
  {
    'name': 'John',
    'age': 30
  },
  {
    'name': 'Bob',
    'age': 50
  },
  {
    'name': 'Tom',
    'age': 14
  },
  {
    'name': 'Donald',
    'age': 3
  }
];

void main(){
  people.removeLast();
  print(people); 
}

Output:

[{name: John, age: 30}, {name: Bob, age: 50}, {name: Tom, age: 14}]

removeRange()

This method removes the items in the range start inclusive to end exclusive:

void removeRange (int start, int end)

Example:

final myList = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];

void main(){
  myList.removeRange(2, 6);
  print(myList);
}

Output:

[a, b, g, h]

Conclusion

Congratulations! At this point, you have learned 5 methods to remove items from a list in Dart and can begin using them in complicated Flutter projects.

You can also read about swiping to remove items from a ListView, highlighting selected items in a ListView, implementing horizontal ListView to get a better sense of list and ListView in Flutter.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles