Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - replacing an item in a list

Tags:

flutter

dart

I have this list of int which has a length of 3

This is the list:

List<Tamount> integer= [
 amount(amount: 2, id: '34'),
 amount(amount: 4, id: '12'),
 TotalAmount(amount: 2, id: '54'),
];

And I want to replace index 2 so the one with the amount of 4

I have tried this :

integer.isNotEmpty
  ? integer.remove(integer[1].id)
  : null;
integers.insert(1, integer(
  id: DateTime.now().toString(),
  amount:34,
));

But it is not working ,for some reason it is not removing it from the list, but it is adding to the list.

like image 601
Chad Avatar asked Sep 05 '20 18:09

Chad


People also ask

How do you replace an element in a List in flutter?

If you know the index of the element you want to replace, you don't need to remove existing element from the List. You can assign the new element by index. Show activity on this post.

How do you replace an object in a List?

We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.

How do you replace data in a List in dart?

You can replace many items with another item using the . replaceRange() method of the dart. You need to provide startIndex, endIndex, and a new list that contains items that need to be updated in the list. In the below example we are replacing items start from 0 indexes to 2 with new values.

How do you find the index of an element in a List in flutter?

In Dart, the List class has 4 methods that can help you find the index of a specific element in a list: indexOf: Returns the first index of the first element in the list that equals a given element. Returns -1 if nothing is found. indexWhere: Returns the first index in the list that satisfies the given conditions.


2 Answers

If you know the index of the element you want to replace, you don't need to remove existing element from the List. You can assign the new element by index.

  integer[1] = amount(amount: 5, id: 'new_id');
like image 62
Pavel Shastov Avatar answered Oct 04 '22 01:10

Pavel Shastov


You can do this:

integer.isNotEmpty
  ? integer.removeWhere((item)=>item.amount == 4) //removes the item where the amount is 4
  : null;
integers.insert(
  1,
  amount(
    id: DateTime.now().toString(),
    amount:34,
  ));

If you want to remove an item by using the index, you can use removeAt() method:

integer.isNotEmpty
  ? integer.removeAt(1) //removes the item at index 1
  : null;
integers.insert(
  1,
  amount(
    id: DateTime.now().toString(),
    amount:34,
  ));
like image 31
Morez Avatar answered Oct 04 '22 01:10

Morez