flutter RangeError(索引):无效值:不在包含范围 0..9:10

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

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): [错误:flutter/lib/ui/ui_dart_state.cc(198)] 未处理的异常: RangeError (index): Invalid value: Not in inclusive range 0..9: 10 E/flutter ( 2732): #0 列表.[] (飞镖:core-patch/growable_array.飞镖:264:36) E/flutter ( 2732): #1 BookService.callGoogleDio (包:book_store/main.dart:41:38) E/flutter ( 2732): E/flutter ( 2732):

我该如何解决这个问题?添加到列表的过程中发生。 未处理的异常:RangeError(索引):无效值:不在包含范围 0..9 中:10

您可以简单地使用 .length 方法正确地迭代结果。

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

或者为了消除代码重复,使用 .forEach()

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