You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中RangeError(index)异常解决方案咨询:索引10不在0..9的有效范围内

解决Flutter调用Google Books API时的RangeError (index)异常

问题原因

你碰到的RangeError (index): Invalid value: Not in inclusive range 0..9: 10异常,核心是数组越界访问。你的代码里硬写了循环20次(i < 20),但Google Books API单次返回的items数组长度可能少于20(比如这次只返回了10条数据,索引范围是0-9),当循环到i=10时,尝试访问map["items"][10]自然就触发了越界错误。

另外还要注意,API返回的items字段有可能为空(比如搜索结果为空时),直接访问map["items"][i]还可能引发空指针问题。

解决方案

我们需要根据API实际返回的items数组长度来控制循环次数,而不是用固定数值。同时增加空值校验,让代码更健壮:

修改后的代码示例

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); 
    // 先获取items列表,为空时赋值空数组避免空指针
    var items = map["items"] ?? []; 
    // 循环次数改为实际items的长度,再也不会越界
    for (int i = 0; i < items.length; i++) { 
      var indexOfMap = items[i]; 
      if (indexOfMap != null) { 
        // 改用items[i]访问,减少重复代码
        String imageUrl = items[i]["volumeInfo"]["imageLinks"]["thumbnail"] ?? ""; 
        String title = items[i]["volumeInfo"]["title"] ?? "empty title"; 
        String subTitle = items[i]["volumeInfo"]["subtitle"] ?? "empty subtitle"; 
        String previewLink = items[i]["volumeInfo"]["previewLink"] ?? ""; 
        print(items[i]); 
        bookList.add(Book( 
          imageUrl: imageUrl, 
          title: title, 
          subTitle: subTitle, 
          previewLink: previewLink)); 
        notifyListeners(); 
      } 
    } 
  } else { 
    print("error"); 
  } 
  return bookList; 
}

进阶优化:获取更多数据(如果需要)

如果你确实想获取最多20条数据,可以在API请求中添加maxResults参数,但依然要以返回的items长度为准(因为总条目可能不足20):

// 修改请求URL,添加maxResults参数指定单次返回数量
Response getGoogleDio = await Dio().get(
  "https://www.googleapis.com/books/v1/volumes?q=${appBarTextController.text}&maxResults=20");

注意:Google Books API单次请求最多返回40条数据,如果需要更多,需要结合startIndex参数实现分页加载。

额外建议

  • 可以使用forEach遍历items,代码会更简洁:
items.forEach((item) {
  if (item != null) {
    // 解析并添加数据到bookList的逻辑
  }
});
  • 对于嵌套的JSON字段访问,建议使用空安全操作符?.进一步避免空指针,比如:
String imageUrl = item["volumeInfo"]?["imageLinks"]?["thumbnail"] ?? "";

内容的提问来源于stack exchange,提问作者justin book

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 22:52:47