How to Remove an Item from Dart List | Flutter

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.

Recent posts