Flutter GetX调用API报错:'String'不是'index'的'int'子类型求助
问题分析与修复方案
核心问题
控制台输出的type 'String' is not a subtype of type 'int' of 'index'是关键错误,根源出在RemoteServices的fetchData方法中:
final productsListJson = (jsonData[''] as List).map((e) => Product.fromJson(e)).toList();
你调用的API返回的是直接的JSON数组,并非嵌套在某个key下的对象。json.decode(response.body)得到的jsonData本身就是List类型,你却用字符串索引jsonData['']去访问——而List只能用整数索引,这直接触发了类型转换错误。
另外,错误发生后进入catch块,但你仅打印了错误信息,未将isLoading设为false,导致加载指示器一直显示。
修复步骤
1. 修正RemoteServices的fetchData方法
直接将jsonData当作List处理,无需通过key索引:
static Future<List<Product>> fetchData() async { final uri = Uri.parse( "https://makeup-api.herokuapp.com/api/v1/products.json?product_type=blush"); final response = await client.get(uri); if (response.statusCode == 200) { var jsonData = json.decode(response.body) as List; // 明确转为List类型 final productsListJson = jsonData.map((e) => Product.fromJson(e)).toList(); print("its WORK SUCCESSFULLY"); return productsListJson; } else { throw Exception('Something Wrong :('); } }
2. 完善错误处理,更新加载状态
在ProductController的fetchProducts方法的catch块中,添加关闭加载状态的逻辑,避免一直显示加载指示器:
void fetchProducts() async { try { var product = await RemoteServices.fetchData(); if (product != null) { productsList.value = product; } isLoading.value = false; // 成功时关闭加载 } catch (e) { print(e); isLoading.value = false; // 错误时也必须关闭加载 } }
额外提示
确保你的Product类的fromJson方法能正确映射API返回的字段,比如API中的image_link要对应类中的imageLink(若使用json_serializable库,需正确配置字段映射),避免因字段不匹配导致后续解析失败。
内容的提问来源于stack exchange,提问作者Marwan
相关产品推荐
相关产品推荐

