how can I remove Models from a list by the index in flutter

35 Views Asked by At

So I have a List with some Models in it

List<add_ingridients_list> added_ingridients_list = [
  add_ingridients_list("a", "b", "c"),
  add_ingridients_list("a", "b", "c"),
  add_ingridients_list("a", "b", "c")
];

and now i want to create a function where i can delete specific models in this list by the index

i came up with a function looking like this

delete_ingredient_from_meal(int i, added_ingridients_list) {
  // i is the index of the ListModel i want to delete
  added_ingridients_list = added_ingridients_list.remove(i);
  return added_ingridients_list;
}

but it isnt working, can someone give me an small example how this function should look like?

1

There are 1 best solutions below

0
Victor Eronmosele On BEST ANSWER

To remove an item from a list based on the item's index, use removeAt instead of remove.

From the List docs:

dart bool remove( Object? value )

[remove] removes the first occurrence of value from this list.

dart E removeAt( int index )

[removeAt] removes the object at position index from this list.

Solution:

Change:

added_ingridients_list = added_ingridients_list.remove(i);

to:

added_ingridients_list.removeAt(i);

Note:

  • removeAt mutates the list and so you don't need to reassign the added_ingridients_list variable.

  • removeAt returns the removed value. To get the removed value, do this:

    final removedItem = added_ingridients_list.remove(i);