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

1,458

Solution 1

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.

Solution 2

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.

Solution 3

try like this:

if(i<=myList.length){
 myList[i]=4;
 }
Share:
1,458
Akbar Pulatov
Author by

Akbar Pulatov

Engineer of Embedded Systems

Updated on December 28, 2022

Comments

  • Akbar Pulatov
    Akbar Pulatov over 1 year
    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?

    • Pratik Butani
      Pratik Butani about 3 years
      You first line of question is wrong. List<myList> = [1,2,3]; in that where is variable name. what is type of list? I think its int as per your given data. Please provide valid infomation.
    • Pratik Butani
      Pratik Butani about 3 years
      Even though I posted my answer (for int). you can check it out.
  • Akbar Pulatov
    Akbar Pulatov about 3 years
    Yes for sure, but, are there more productive way to do it, just out of box? If not this is an option.
  • Randal Schwartz
    Randal Schwartz about 3 years
    myList = myList.map((e) => e == 2 ? 4 : e).toList();