Flutter类型转换错误:期望int类型却获取到String类型
解决Flutter解析API时的类型转换错误:Expected a value of type 'int', but got one of type 'String'
问题根源
你的错误是因为API返回的id字段为字符串类型,但你在Course实体类中把id定义为int类型,直接用as int强制转换字符串会触发类型不匹配异常。
解决方案
修改Course类的fromJson工厂方法,将字符串类型的id安全转换为整数:
import 'package:equatable/equatable.dart'; import 'package:corsiapp/Domain/Course/lesson.dart'; class Course extends Equatable { const Course( {required this.id, required this.title, required this.urlImage, required this.description}); final int id; final String title; final String urlImage; final String description; factory Course.fromJson(Map<String, dynamic> json) { return Course( // 用tryParse避免非数字字符串导致崩溃,可根据业务调整默认值 id: int.tryParse(json['id'] as String) ?? 0, title: json['title'] as String, urlImage: json['urlimage'] as String, description: json['description'] as String); } @override List<Object?> get props => [id, title, urlImage, description]; }
额外调试建议
如果后续还有类似类型错误,可在RemoteDataSourceImpl的getCoursefromAPI方法中打印API返回的原始数据,快速定位字段类型问题:
@override Future<List<Course>> getCoursefromAPI() async { final response = await client .get(Uri.parse('https://638c1e60eafd555746a0b852.mockapi.io/Course')); if (response.statusCode == 200) { print(response.body); // 打印原始响应,确认字段类型 return parseCourse(response.body); } else { print('Serch Local Repository'); throw Exception(); } }
内容的提问来源于stack exchange,提问作者Aitor Parrilla
相关产品推荐
相关产品推荐

