首页 > 解决方案 > 如何在指定索引中添加值?

问题描述

我有数据集列表。

List<Model> list = [];

...

有一些过程可以将数据添加到列表中。

我想将索引传递给该方法。我想替换数据。

我尝试了这 3 种方法,但没有替换..添加另一个新值。

list.insert(widget.configureIndex, model);//1

list[widget.configureIndex] = model;//Error: RangeError (index): Invalid value: Only valid value is 0: 1

list.replaceRange(widget.configureIndex, widget.configureIndex, [model]);//3

标签: flutterdart

解决方案


我认为您遇到的问题是您的列表在您尝试替换的索引处没有值。

List<Model> list = [];
int configureIndex = 2;
// None of these work because your list is empty to begin with. 
emptyList.insert(configureIndex, model);
emptyList[configureIndex] = model;
emptyList.replaceRange(configureIndex, configureIndex, [model]);


// Your list must have a value at the index you want to replace

list = [model, model, model]; // list now has value at index 2
if(list.length > configureIndex) { // These will work!
  emptyList.insert(configureIndex, model);
  emptyList[configureIndex] = model;
  emptyList.replaceRange(configureIndex, widget.configureIndex, [model]);
}

推荐阅读