Flutter - 替换列表中的项目

Cha*_*had 14 dart flutter

我有int一个长度为 3 的列表

这是清单:

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

我想替换索引 2,所以数量为 4

我试过这个:

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

但它不起作用,出于某种原因,它没有将其从列表中删除,而是添加到列表中。

Pav*_*tov 24

如果您知道要替换的元素的索引,则无需从 List 中删除现有元素。您可以通过索引分配新元素。

  integer[1] = amount(amount: 5, id: 'new_id');
Run Code Online (Sandbox Code Playgroud)

  • 经过 5 年的编程,我开始忘记一些基础知识了 XD。谢谢 。 (17认同)
  • @evals 我们都得出了相同的结论 xD (5认同)

Mor*_*rez 10

你可以这样做:

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,
  ));
Run Code Online (Sandbox Code Playgroud)

如果要使用索引删除项目,可以使用removeAt()方法:

integer.isNotEmpty
  ? integer.removeAt(1) //removes the item at index 1
  : null;
integers.insert(
  1,
  amount(
    id: DateTime.now().toString(),
    amount:34,
  ));
Run Code Online (Sandbox Code Playgroud)