Flutter调用API转换List<dynamic>报错,需获取ProblemWithCommentModel列表
问题解决:Expected a value of type 'List', but got one of type '_JsonMap'
问题分析
错误根源在于你请求的https://localhost:7050/api/Problem/1接口返回的是单个Problem对象(_JsonMap类型),但你在代码里强行将其转换为List<dynamic>,导致类型不匹配。之前用List处理有效是因为当时请求的是列表接口(如/api/Problem不带ID),但本次是带ID的详情接口,返回的是单个实体。
修复方案
场景1:获取单个对象并包装为列表
如果你的业务确实需要将单个接口返回的对象转为ProblemWithCommentModel类型的列表,修改getProblem方法如下:
Future<void> getProblem() async { final response = await dio.get('https://localhost:7050/api/Problem/1', options: Options( headers: {"content-type": "application/json"}, )); // 先将单个JSON对象转为模型实例,再放入列表 final singleProblem = ProblemWithCommentModel.fromJson(response.data as Map<String, dynamic>); final problemList = [singleProblem]; print(problemList); }
场景2:获取多个Problem对象的列表
如果你的目标是获取列表,需确认接口地址是否正确,应该请求不带ID的列表接口:
Future<void> getProblem() async { final response = await dio.get('https://localhost:7050/api/Problem', // 移除末尾的/1 options: Options( headers: {"content-type": "application/json"}, )); final problemsJsonList = response.data as List<dynamic>; final problemList = problemsJsonList.map((e) => ProblemWithCommentModel.fromJson(e as Map<String, dynamic>)).toList(); print(problemList); }
额外代码修正
你的Comments类存在语法错误,part of 'Comments.dart';需放在文件开头而非类内部,修正后的示例代码:
part of 'Comments.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** class Comments { final String userName; final int id; final int userId; final int problemId; final String about; final String date; Comments({ required this.userName, required this.id, required this.userId, required this.problemId, required this.about, required this.date, }); factory Comments.fromJson(Map<String, dynamic> json) => _$CommentsFromJson(json); Map<String, dynamic> toJson() => _$CommentsToJson(this); } Comments _$CommentsFromJson(Map<String, dynamic> json) => Comments( userName: json['userName'] as String, id: json['id'] as int, userId: json['userId'] as int, problemId: json['problemId'] as int, about: json['about'] as String, date: json['date'] as String, ); Map<String, dynamic> _$CommentsToJson(Comments instance) => <String, dynamic>{ 'userName': instance.userName, 'id': instance.id, 'userId': instance.userId, 'problemId': instance.problemId, 'about': instance.about, 'date': instance.date, };
内容的提问来源于stack exchange,提问作者Aidars Show
相关产品推荐
相关产品推荐

