Flutter: I want to assign values of String from each for loop in to a list of Strings in flutter but getting error that invalid range

Issue

List<String> path = <String>[];
loopRun(int i) {
    for (int i = 0; i < 2; i++) {
      print("Called");
      
      _getData(
          files[i].toString(), i);
    }
  }
_getData(file, int i) async {    
    String thumb = file;
    print(thumb); 
    path[i] = thumb;
    print(path[i]);
    setState(() {      
    });
    return thumb;
  }

In the above code, I am calling the loopRun(3) and the loop is running three times and I am seeing the value of thumb in the console which are returning 3 strings. I have to assign each String of thumb in path. For that I declared empty String list path and trying to assign in path[i] but getting the below error.

E/flutter (15093): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 0
E/flutter (15093): #0      List._setIndexed (dart:core-patch/growable_array.dart:262:73)
E/flutter (15093): #1      List.[]= (dart:core-patch/growable_array.dart:258:5)
E/flutter (15093): #2      _MyHomePageState._getData
package:dtp22/main.dart:124
E/flutter (15093): <asynchronous suspension>
E/flutter (15093):

E/flutter (15093): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 1
E/flutter (15093): #0      List._setIndexed (dart:core-patch/growable_array.dart:262:73)
E/flutter (15093): #1      List.[]= (dart:core-patch/growable_array.dart:258:5)
E/flutter (15093): #2      _MyHomePageState._getData
package:dtp22/main.dart:124
E/flutter (15093): <asynchronous suspension>
E/flutter (15093):

Solution

if you want to insert an element at a specific index which I think you are trying to achieve by

path[i] = thumb;

is not the right way, instead use the insert function, which for your case will look like

path.insert(i, thumb);

Answered By – Devanshu Kumar Singh

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *