Dart报错:参数类型'String'无法分配给参数类型'Uri'求助
解决Flutter网络请求的两个问题:Uri类型错误与数据无法打印
1. 修复"The argument type 'String' can't be assigned to the parameter type 'Uri'"错误
http包的get()方法要求传入Uri类型参数,而非字符串。只需将拼接好的API地址转换为Uri对象即可,最简单的方式是使用Uri.parse():
修改网络请求代码如下:
@override Future<List<MovieModel>> getTrending() async { final response = await _client.get( // 用Uri.parse包裹字符串地址 Uri.parse('${ApiConstants.BASE_URL}trending/movie/day?api_key=${ApiConstants.API_KEY}'), headers: { 'Content-Type': 'application/json', }, ); // 后续代码保持不变... }
如果想更规范地构建Uri(避免手动拼接参数时的编码问题),可以用Uri.https()拆分域名、路径和查询参数:
// 假设ApiConstants新增BASE_HOST(如 'api.themoviedb.org')和BASE_PATH(如 '/3')字段 final response = await _client.get( Uri.https( ApiConstants.BASE_HOST, '${ApiConstants.BASE_PATH}/trending/movie/day', {'api_key': ApiConstants.API_KEY}, ), headers: { 'Content-Type': 'application/json', }, );
2. 解决获取到的数据无法打印的问题
如果print(movies)没有输出预期的电影数据,通常有两个原因:
原因1:MovieModel未重写toString()方法
默认情况下,打印对象只会输出Instance of 'MovieModel'这类实例标识,不会显示具体属性。需要在MovieModel类中重写toString():
class MovieModel { // 你的类属性 final int id; final String title; final String? posterPath; MovieModel({required this.id, required this.title, this.posterPath}); // 重写toString,打印属性内容 @override String toString() { return 'MovieModel(id: $id, title: $title, posterPath: $posterPath)'; } // 其他方法(fromJson等)... }
原因2:接口返回数据解析不匹配
可以先打印原始响应数据,确认接口返回结构是否与MoviesResultModel匹配:
if (response.statusCode == 200){ final responseBody = json.decode(response.body); print('原始接口返回:$responseBody'); // 先验证原始数据是否正确 final movies = MoviesResultModel.fromJson(responseBody).movies; print('解析后的电影列表:$movies'); return movies; }
如果原始数据正确但解析后movies为空,检查MoviesResultModel的fromJson方法是否正确映射了接口字段(比如接口里的results字段是否对应模型里的movies属性)。
内容的提问来源于stack exchange,提问作者user21368788
相关产品推荐
相关产品推荐

