How to Remove an Item from Dart List | Flutter

Created At: 2022-03-19 02:32:44 Updated At: 2023-06-15 07:36:50

Map and List are one of the most important concept for Dart and Flutter app development. Once you know the basics of Map and List, it will make your life easier. 

We use List a lot internally flutter framework and you must to some basics ussage of List like declaring, adding and removing items from list.

5 Different ways to remove items from a List in Flutter Dart

Using removeAt() based on index

  List myList = [1,2,3,4,5];
  
  myList.removeAt(2);
  
  print(myList);         // [1, 2, 4, 5]
  print(myList.length);  //  4

So if you want to remove the first Item, then you will send 0 for removeAt().

removeAt(0) //removes the first item

removeAt(1) //removes the second item

Using remove() based on item's value

  List myList = [1,2,3,4,5];
  
  bool result = myList.remove(2);
  
  print(myList);  // [1, 3, 4, 5]
  print(result);  // true
  print(myList.length);  // 4

This is used often in flutter framework when you make a post request to remove items.

 

Using removeLast() to remove the last item

  List myList = [1,2,3,4,5];
  
  var result = myList.removeLast();
  
  print(myList);  // [1, 2, 3, 4]
  print(result);  // 5
  print(myList.length);  // 4

 

Remove last n items length-n method

  List myList = [1,2,3,4,5];
  
  int howMany = 2;
  
  myList.length = myList.length - howMany;
  
  print(myList);  // [1, 2, 3]
  print(myList.length);  // 3

 

Remove based on condition using removeWhere()

  List myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  
  
  myList.removeWhere((item) => item % 2 == 0);
  
  print(myList);  // [1, 3, 5, 7, 9]
  print(myList.length);  // 5

This one is super important in flutter programming.

Spread opeator and remove item

If you have list, and you want to update this using spread operator, then below is the way to go.

void removeAnItem(int index){
  state.removeAt(index);
  state = [...state];
}

Here state is stateful list. In Flutter framework we use a stateful list all the time. Here we remove at item at first. Then this list would be auto updated. 

but we also need to assign it state variable again. Otherwise UI won't get the latest value. So we assign it using spread operator.

The above kind of spread operator is used if you use Riverpod as state management system.

Comment

Add Reviews