Chad
Chad

Reputation: 685

Flutter - replacing an item in a list

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.

Upvotes: 58

Views: 68439

Answers (4)

Emile
Emile

Reputation: 11721

I made the mistake of passing in a List as a Widget parameter and then assigning that to the stateful widgets internal instance. This actually makes the list immutable.

i.e. within a stateful widgets init();

  List<NewOption> selectableOptions
  @override
  void initState() {
    super.initState();
    selectableOptions = widget.selectableOptions;
  }

If you try to do the selectableOptions[index] = NewOption() line, it will fail with

flutter Unsupported operation: Cannot modify an unmodifiable list

So instead you'll need to call

  @override
  void initState() {
    super.initState();
    selectableOptions = widget.selectableOptions.toList();
  }

Note: this makes me think this is a terrible idea, but worth noting.

Upvotes: 0

Omar Khaled
Omar Khaled

Reputation: 191

In addition, if you want to replace an item at a specific unknown index, you can use indexWhere() method:

final index = integers.indexWhere((amount) => amount.id == 4);
integers[index] = Tamount(amount: 3, id: 'ID');

Upvotes: 9

Pavel Shastov
Pavel Shastov

Reputation: 3017

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');

Upvotes: 99

Morez
Morez

Reputation: 2229

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,
  ));

Upvotes: 12

Related Questions