Break out of For loop for invalid image link Flutter

Viewed 678

I am trying to create a book with the chapter's contents via images. Images links are in below manners:

https://www.someurl.com/chapter1/1.jpg https://www.someurl.com/chapter1/2.jpg https://www.someurl.com/chapter1/3.jpg . . .

Not sure how many image links per chapter. I am creating a list of images using a loop. As it iterates and finally image is not found, it will display a button usingerrorWidget for next chapter and should break out of the loop. With below implementation Images are being displayed correctly but not breaking out of the loop and multiple buttons are created.

Edit: I am now checking for image validation at the end. Now it displays only one image but prints 200 (statuscode) until once invalid and breaks out of loop.

 createBook() async {
    for(int i=1; i<100; i++){
      bool imageEnd = false;
      String imageUrl = 'https://www.someurl.com/chapter1/'+i+'.jpg';
      bookList.add(CachedNetworkImage(
        imageUrl: imageUrl,
        fit: BoxFit.cover,
        placeholder: (context, url) => Container(child: Center(child: CircularProgressIndicator())),
        errorWidget: (context, url, error) {
          imageEnd = true;
          return BtnNextChapter();
          },
      ));
      if(imageEnd){
        break;
      }
      final response = await http.get(imageUrl);
      print(response.statusCode);
      if (response.statusCode != 200) {
        break;
      }
    }
    }

enter image description here

1 Answers

Logically, you should have a way to know how many books are there per chapter and should iterate those many times. However to fix your code, try the below.

  createBook(){
    for(int i=1; i<100; i++){
      final imageUrl = 'https://www.someurl.com/chapter1/'+i+'.jpg';
      final response = await http.get(imageUrl);
      print(response.statusCode);

      if (response.statusCode != 200) {
        bookList.add(BtnNextChapter());
      } else{
        bookList.add(CachedNetworkImage(
          imageUrl: imageUrl,
          fit: BoxFit.cover,
          placeholder: (context, url) => Container(child: Center(child: CircularProgressIndicator())),
        );
      }
     }
   }

With the above code, you will miss the images if there are more than 100 migaes in any chapter.

Related