Home > Software design >  Flutter#7 RangeError (RangeError (index): Invalid value: Valid value range is empty: 0)
Flutter#7 RangeError (RangeError (index): Invalid value: Valid value range is empty: 0)

Time:11-11

i'm trying to print out a list of images

    Future<void> getDeviceImage() async {
    var api = TechAPI.shared;
    var res = await api.getDeviceImage();
    var dataResponse = DataResponse.fromJson(res);
    print(dataResponse.toJson());
    List<dynamic> dt = jsonDecode(jsonEncode(dataResponse.data));
    print(dt);
    list.add(dt);
  }
List<dynamic> list = [];
list[0]; // <-- Error since there's no element at index 0 in the list. 

I will get an error which is :

RangeError (RangeError (index): Invalid value: Valid value range is empty: 0)

However when I hot - reload in VS code. my list just returns data

How can I fix this without having to hot-reload it.

CodePudding user response:

This might help :

Initialize the list as :

List<dynamic> list=[];

Your function:

Future<void> getDeviceImage() async {
var api = TechAPI.shared;
await api.getDeviceImage().then((res){
var dataResponse = DataResponse.fromJson(res);
print(dataResponse.toJson());
setState((){
list =List<dynamic>.from(jsonDecode(jsonEncode(dataResponse.data)));
 });
});
    }
  • Related