简体   繁体   中英

flutter RangeError (index): Invalid value: Not in inclusive range 0..4: 5 on CarouselSlider

I want to show the all images from the API in the carousel and for items, I want to show 2 items per slide. and it works correctly what I want. but in every last item, it shows me the error of CarouselSlider . I don't know why it gives me this error. I tried to solve it but failed because I don't know why they give me this error in the last item.

here is my code:-

import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';

class PersonImages extends StatefulWidget {

 PersonImages({Key? key}) : super(key: key);

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

class _PersonImages extends State<PersonImages>{

 var UsriD = Auth.prefs?.getString('usrid');
 var Imagedata;
 var img = "";
 var user = "";

 @override
 void initState() {
  super.initState();
 getImageData();
 }

 getImageData() async{
  var res = await http.get(Uri.https('www.*******.net', '/index.php',{'act':'usrPhotos','Usrid': '${UsriD}'}));
 Imagedata = jsonDecode(res.body);
 //print(Imagedata);
 setState(() {});
 print(res.body);
}

@override
Widget build(BuildContext context) {
//print(Imagedata);

return
  Imagedata != null? CarouselSlider.builder(
      options: CarouselOptions(
        //height: 150,
        aspectRatio: 2.0,
        enableInfiniteScroll: false,
        //viewportFraction: 0.8,
        enlargeCenterPage: true,
        viewportFraction: 1,
      ),
      itemCount: (Imagedata.length / 2).round(),
      //itemCount: 3,
      itemBuilder: (BuildContext context, int index, int  pageViewIndex) {
        final int first = index * 2;
        final int second = first + 1;
        return
          Row(
            children: [first, second].map((idx) {
              return Expanded(
                //flex: 2,
                child:  Container(
                child: Container(
                  margin: EdgeInsets.all(5.0),
                    child: ClipRRect(
                      borderRadius: BorderRadius.all(Radius.circular(8.0)),
                      child:
                      Image.network(
                        "https://www.*******.net/files/images/${Imagedata[idx]['image']}",
                        fit: BoxFit.cover,
                        width: 200,
                        height: 200,
                      ),
                    ),

                ),
              )
              );
            }).toList(),
          );
      }
  ): const Center(
    child: CircularProgressIndicator(),
  );
  }
  }

Here is my error and output :- 错误和输出

please help me if anyone knows how to resolve it. is anyone knows how to do this so answer my question?

In case of an odd number length, for example 5

you divided it by 2. which is 2.5 Rounded it then the value is 3.

Now when it loops for the third time. It will try and fetch 2*2 + 1. now you will try and find the element by id 5 which doesn't exist. You can try

 itemCount: (Imagedata.length / 2).floor(),

Note you may lose the last image in case of an odd length.

Try checking null like

Imagedata[idx]['image']!= null?
 Image.network("...${Imagedata[idx]['image']}", ) 
       :Text("cant find image index"),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM