Home > Software design >  RangeError for list in flutter
RangeError for list in flutter

Time:01-08

I am working on an app that requires me to display images from an API. It has been working fine till today morning. Today I edited some parts to pass the image to another page and tried running it. It gave the following error:

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

I undid all the changes that I made and am still getting this error.

I understand that the problem is that the list to display the image is empty. But I don't get why it is empty now when it was working fine before.

Has anyone else faced this issue?

Any help would be appreciated. Thanks in advance.

Before output:

output 1

The output that I'm getting now:

output 2

<here it shows "The index is 0" since I added a new container in the column to check the index>

Code to display the images:

class wpList extends StatefulWidget {
  const wpList({Key? key}) : super(key: key);

  @override
  _wpListState createState() => _wpListState(); 
}


class _wpListState extends State<wpList> {

  final wpControl = Get.put(wpController());
  List data = [];

  List<String> wpUrl= [];
  // List<String> wpUrl1=[];
  bool showing = false;
  var ifliked= 'Like image';


  @override
  Widget build(BuildContext context) {

    ApiService().getMethod('https://api.unsplash.com/photos/?client_id=<API KEY>');
     return  ListView.builder(
            itemCount: 10,
            itemBuilder: (context, index){
              return Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    child: Text(
                      'The index is $index'
                    ),
                  ),
                  SizedBox(
                    height: 10,
                  ),

                  Obx(
                    ()=> GestureDetector(
                      onTap: (){
                        Get.to(wpView(index: index));
                      },
                      child: Container(
                          // color: Colors.grey,
                          //     height: 100,
                              child: Image(
                                image: NetworkImage(wpControl.imgs[index].urls!['regular'])
                              ),
                   
                        ),
                    ),
                  ),

                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      primary: Colors.teal,
                      onPrimary: Colors.white,
                      shadowColor: Colors.greenAccent,
                      elevation: 3,
                      // shape: RoundedRectangleBorder(
                      //     borderRadius: BorderRadius.circular(32.0)),
                      minimumSize: Size(300, 40), //////// HERE
                    ),
                    onPressed:(){
                      print("The button $index is pressed");
                      wpControl.sindex.value=index;
                      // setState(() {
                      //   ifliked='Liked';
                      // });
                    },
                    child: Text(
                      '$ifliked'
                    ),
                  ),
                  SizedBox(
                    height: 20,
                  )
                ],
              );
            });
  }
}

Api service code:

import 'package:dio/dio.dart';
import 'dart:developer';

class ApiService{
  Future<dynamic> getMethod(String url) async{
    Dio dio = Dio();
    dio.options.headers['content-Type'] = 'application/json';
    return await dio.get(url,
    options: Options(responseType: ResponseType.json, method: "GET")
    ).then((value){
      log(value.toString());
      return value;
    }); 
  }
}

GetX Controller code

import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'api_service.dart';
import 'images.dart';

class wpController extends GetxController{
//list of wps
//var wpUrl = List<Imagess>().obs;
  RxList<Imagess> imgs = RxList();

  var sindex = 0.obs;

  getImages() async{
    var response = await 
    ApiService().getMethod('https://api.unsplash.com/photos/?client_id= <API KEY>');
    print('response.statusCode');
    if(response.statusCode == 200){
      response.data.forEach((elm){
        imgs.add(Imagess.fromJson(elm));
        print('imgs');
      });
    }
  }

  @override
  void onInit(){
    getImages();
    super.onInit(); 
  }
}

Imagess class:

class Imagess{
  String? id;
  String? createdAt;
  String? color;
  Map<String, dynamic>? urls;

  Imagess({
    this.id,
    this.createdAt,
    this.color,
    this.urls
});

  Imagess.fromJson(Map<String, dynamic> json){
    id = json['id'];
    createdAt = json['created_at'];
    color = json['color'];
    urls = json['urls'];
  }
}

Debug console output: enter image description here

Debug console output 2 : enter image description here

CodePudding user response:

I think you should change the itemCount with wpControl.imgs.length just in case if the response send no data or the image is null the listview.builder will not force to create 10 item and throws an error but it will count how many image data you got from the response

CodePudding user response:

  • the url Type maybe is List
 var json =
        '{"id":"1","createAt":"20220101","color":"blue","urls":["url1","url2","url3"]}';
 var model = Imagess.fromJson(jsonDecode(json));
 print(model.urls);
 // print result : [url1, url2, url3]


class Imagess {
  String? id;
  String? createdAt;
  String? color;
  List<dynamic>? urls;

  Imagess({this.id, this.createdAt, this.color, this.urls});

  Imagess.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    createdAt = json['created_at'];
    color = json['color'];
    urls = json['urls'];
  }
}


  • if the url Type is Map . you can try this code
 var json =
        '{"id":"1","createAt":"20220101","color":"blue","urls":{"data":["url1","url2","url3"]}}';
 var model = Imagess.fromJson(jsonDecode(json));
 print(model.urls);
 // print result : "data":[url1, url2, url3]

class Imagess {
  String? id;
  String? createdAt;
  String? color;
  UrlModel? urls;

  Imagess({this.id, this.createdAt, this.color, this.urls});

  Imagess.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    createdAt = json['created_at'];
    color = json['color'];
    urls = UrlModel.fromJson(json['urls']);
  }
}

class UrlModel {
  List<dynamic>? data;
  UrlModel(this.data);
  UrlModel.fromJson(Map<String, dynamic> json) {
    data = json['data'];
  }
}


  • Related