Home > other >  flutter RangeError (index): Invalid value: Not in inclusive range 0..9: 10
flutter RangeError (index): Invalid value: Not in inclusive range 0..9: 10

Time:05-31

List<Book> bookList = [];

  BookService();

  final TextEditingController appBarTextController = TextEditingController();

  Future<List<Book>> callGoogleDio() async {
    Response getGoogleDio = await Dio().get(
    "https://www.googleapis.com/books/v1/volumes?q=${appBarTextController.text}");

if (getGoogleDio.statusCode == 200) {
  var map = getGoogleDio.data;
  int totalItems = map["totalItems"];
  print(totalItems);

  for (int i = 0; i < 20; i  ) {
    var indexOfMap = map["items"][i];
    if (indexOfMap != null) {
      String imageUrl =
          map["items"][i]["volumeInfo"]["imageLinks"]["thumbnail"] ?? "";
      String title = map["items"][i]["volumeInfo"]["title"] ?? "empty title";
      String subTitle =
          map["items"][i]["volumeInfo"]["subtitle"] ?? "empty subtitle";
      String previewLink = map["items"][i]["volumeInfo"]["previewLink"] ?? "";
      print(map["items"][i]);

      bookList.add(Book(
          imageUrl: imageUrl,
          title: title,
          subTitle: subTitle,
          previewLink: previewLink));
      notifyListeners();
    }
  }
} else {
  print("error");
}
return bookList;
}

E/flutter ( 2732): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: RangeError (index): Invalid value: Not in inclusive range 0..9: 10 E/flutter ( 2732): #0 List.[] (dart:core-patch/growable_array.dart:264:36) E/flutter ( 2732): #1 BookService.callGoogleDio (package:book_store/main.dart:41:38) E/flutter ( 2732): E/flutter ( 2732):

How can I solve this problem? Occurred during the process of adding to the list. Unhandled Exception: RangeError (index): Invalid value: Not in inclusive range 0..9: 10

CodePudding user response:

You can simply use .length method to iterate properly through the result.

for(var i = 0; i < map["items"].length; i  ){...}

Or to get rid of code duplication, use a .forEach()

map["items"].forEach((item) {...})
  • Related