Flutter使用Dio与Retrofit解析API模型时类型转换报错求助
Flutter中使用Dio+Retrofit解析键值对格式的API响应
问题根源
你的API返回的是键为时间段、值为价格数据的Map结构,但Retrofit接口定义成了返回List<PriceModel>,直接导致类型不匹配,抛出_InternalLinkedHashMap无法转成List的错误。另外,API字段用短横线命名(如is-cheap),和Dart模型的驼峰命名(isCheap)未做映射,解析后这些字段会是null。
解决步骤
1. 修正PriceModel的字段映射
给模型中对应字段添加@JsonKey注解,匹配API返回的字段名:
import 'package:json_annotation/json_annotation.dart'; part 'price_model.g.dart'; @JsonSerializable() class PriceModel { String? date; String? hour; @JsonKey(name: "is-cheap") bool? isCheap; @JsonKey(name: "is-under-avg") bool? isUnderAvg; String? market; double? price; String? units; PriceModel({ this.date, this.hour, this.isCheap, this.isUnderAvg, this.market, this.price, this.units, }); factory PriceModel.fromJson(Map<String, dynamic> json) => _$PriceModelFromJson(json); Map<String, dynamic> toJson() => _$PriceModelToJson(this); }
2. 调整Retrofit接口的返回类型
将接口返回类型改为Map<String, PriceModel>,对应API的实际结构:
import 'package:electricity_price/app/home/models/price_model.dart'; import 'dart:async'; import 'package:dio/dio.dart'; import 'package:retrofit/http.dart'; part "price_repository.g.dart"; @RestApi() abstract class PriceRepository { factory PriceRepository(Dio dio, {String baseUrl}) = _PriceRepository; @GET('all?zone=PCB') Future<Map<String, PriceModel>> getPrices(); }
3. (可选)将Map转为List使用
如果业务逻辑需要List格式,获取数据后把Map的values转为List即可:
final priceMap = await priceRepository.getPrices(); final priceList = priceMap.values.toList();
重新生成代码
修改完模型和接口后,执行命令重新生成序列化代码:
flutter pub run build_runner build
内容的提问来源于stack exchange,提问作者Br0wn
相关产品推荐
相关产品推荐

