Flutter调用Cat API报错:预期int类型,需获取String类型URL
问题描述
调用The Cat API获取图片URL时,URL明显是String类型,但代码提示预期int类型的值,不清楚哪个值需要是整数,明明图片加载需要的是String类型的URL。

原代码
页面Widget代码
import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; import '../models/catdata.dart'; class Apicat extends StatefulWidget { Apicat({Key? key}) : super(key: key); @override State<Apicat> createState() => _ApicatState(); } class _ApicatState extends State<Apicat> { Future<List<CatData>> fetchCatdata() async { final response = await http.get(Uri.parse( 'https://api.thecatapi.com/v1/images/search?limit=22&breed_ids=beng&api_key=f9891ce2-f1db-425d-bed0-0dcc1eb8be97')); if (response.statusCode == 200) { // If the server did return a 200 OK response, // then parse the JSON. final data = jsonDecode(response.body); // este es un array de Strings final list = data['url'] as List; //final list2 = data['origin'] as List; // pasa la data a objetos catData, recorriendo los strings y transformandolos a objeto //final listCatData = list.map((item) => CatData(imagen: item)).toList(); return list.map((e) => CatData(imagen: e)).toList(); //return list.map((e) => CatData(imagen: e, origen: list2[0])).toList(); } else { // If the server did not return a 200 OK response, // then throw an exception. throw Exception('Failed to load album'); } } @override Widget build(BuildContext context) { return FutureBuilder<List<CatData>>( future: fetchCatdata(), builder: (BuildContext context, AsyncSnapshot<List<CatData>> snapshot) { if (snapshot.hasData) { //crea dos listas de catData, una para la imagen y otra para la descripcion final list = snapshot.data!; //final list2 = snapshot.data!; return ListView.builder( itemCount: list.length, itemBuilder: (BuildContext context, int index) { return Image.network(list[index].imagen); }, ); } else if (snapshot.hasError) { return Text("${snapshot.error}"); } // By default, show a loading spinner. return CircularProgressIndicator(); }, ); } }
CatData模型类
class CatData{ final String imagen; CatData({required this.imagen}); factory CatData.fromJson(Map<String, dynamic> json) { return CatData( imagen: json['url'], ); } }
错误原因
核心问题出在fetchCatdata方法的解析逻辑:
- The Cat API返回的是对象数组(每个元素包含
url字段),但你错误地尝试从数组data中直接取data['url'],这会返回null。 - 后续将
null强制转换为List时触发类型错误,导致映射CatData时传入的不是预期的String类型URL,最终引发"预期int类型"的错误提示。
修正方案
调整fetchCatdata方法的解析逻辑,正确处理API返回的对象数组:
Future<List<CatData>> fetchCatdata() async { final response = await http.get(Uri.parse( 'https://api.thecatapi.com/v1/images/search?limit=22&breed_ids=beng&api_key=f9891ce2-f1db-425d-bed0-0dcc1eb8be97')); if (response.statusCode == 200) { // 将返回的JSON转为对象数组 final List<dynamic> dataList = jsonDecode(response.body); // 遍历数组,用模型类的fromJson方法解析每个对象 return dataList.map((json) => CatData.fromJson(json as Map<String, dynamic>)).toList(); } else { throw Exception('Failed to load cat images'); } }
说明:
- 直接解析API返回的数组,无需尝试获取不存在的
data['url']。 - 使用
CatData.fromJson工厂方法解析每个对象,保证imagen字段为String类型,与Image.network的参数要求匹配。
内容的提问来源于stack exchange,提问作者yorman lopez
相关产品推荐
相关产品推荐

