Flutter解析API返回的gallery数组内url字段报错如何正确取值
解析错误核心原因
现有代码存在两处逻辑问题导致解析失败:
- 未处理接口返回结构最外层的
data包裹节点,直接从根JSON对象读取id、gallery字段,实际业务字段全部嵌套在data对象下 gallery字段为数组结构(JSON中以[]包裹),并非单层键值对象,无法直接通过json['gallery']['url']读取属性,需要遍历数组项获取对应字段值
正确实现步骤
1. 定义画廊单条数据模型
不要使用动态类型List存储gallery数据,先定义单条画廊项的模型,提前做类型转换,避免后续使用时出现类型错误:
class GalleryItem { final String url; final String mimeType; final String type; final String updatedAt; final String createdAt; GalleryItem({ required this.url, required this.mimeType, required this.type, required this.updatedAt, required this.createdAt, }); factory GalleryItem.fromJson(Map<String, dynamic> json) { return GalleryItem( url: json['url'] as String, mimeType: json['mime_type'] as String, type: json['type'] as String, updatedAt: json['updated_at'] as String, createdAt: json['created_at'] as String, ); } }
2. 修正User模型解析逻辑
解析时先读取外层data节点,再遍历gallery数组完成类型转换:
class User { final int id; final String? pictureUrl; final bool emailConfirmed; final List<GalleryItem> gallery; final String updatedAt; final String createdAt; User({ required this.id, this.pictureUrl, required this.emailConfirmed, required this.gallery, required this.updatedAt, required this.createdAt, }); factory User.fromJson(Map<String, dynamic> rootJson) { // 提取内层data节点 final Map<String, dynamic> data = rootJson['data'] as Map<String, dynamic>; // 转换gallery数组 final List<dynamic> galleryRaw = data['gallery'] as List<dynamic>; final List<GalleryItem> galleryList = galleryRaw .map((item) => GalleryItem.fromJson(item as Map<String, dynamic>)) .toList(); return User( id: data['id'] as int, pictureUrl: data['picture_url'] as String?, emailConfirmed: data['email_confirmed'] as bool, gallery: galleryList, updatedAt: data['updated_at'] as String, createdAt: data['created_at'] as String, ); } }
3. 读取图片url的使用方式
解析完成后可直接通过对象属性访问需要的链接,使用前注意判断数组长度避免越界:
// 解析接口响应 final Map<String, dynamic> responseJson = jsonDecode(response.body); final User user = User.fromJson(responseJson); // 获取第一张图片的url if (user.gallery.isNotEmpty) { String firstImgUrl = user.gallery[0].url; // 传入后续业务逻辑使用即可 } // 如果需要获取全部图片链接,可直接映射得到url列表 List<String> allImgUrls = user.gallery.map((item) => item.url).toList();
提示:如果业务中不需要
mime_type、created_at等冗余字段,可以在GalleryItem模型中删除对应属性,只保留需要的url字段即可,不影响解析逻辑。
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

