Flutter. Dart. Flutter - replacing a item in a list

Viewed 2218
List<int> myList = [1,2,3];
int i = 2;
myList[i] = 4; // myList = [1,2,4]

but what if i don't know whether myList contains data at specific index? Then it gives me range error.

i = 4;
myList[i] = 4 // range error
if(myList[i] != null) myList[i] = 4 //range error
myList.insert(i, 4) // i want to replace, not shift values.

Is the only way to replace the list value at specific index is by checking the whole list length first?

3 Answers

Here is the example that you can check the index before and If that condition is true then only it will update the value.

void main() {
  List<int> myList1 = [1,2,3];
  int i = 2;
  if(myList1.length> i) myList1[i] = 4; // myList = [1,2,4]
  myList1.forEach(print);
  
  
  int j = 5;
  if(myList1.length> j) myList1[j] = 4; // myList = [1,2,4]
  myList1.forEach(print); // It will print as it is last one.
}

Thank you.

From what I understood, you want to know if there is any other way to check whether or not the index exists for your list. If So then:

List<int> myList = [1,2,3];
int i = 2;
if(myList.asMap().containsKey(i)) myList[i] = 4

Let me know if I understood your question correctly.

try like this:

if(i<=myList.length){
 myList[i]=4;
 }
Related