You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter网络请求解析报错求助:两类类型不匹配问题

问题修复方案

错误原因分析

  • 错误1:Post.fromJson()方法返回单个Post实例,但你试图将其赋值给List<Post>类型变量,类型不匹配。
  • 错误2:response.body是原始字符串,而fromJson()方法要求传入Map<String, dynamic>类型参数,直接传字符串会导致类型兼容问题。

修复后的代码

import 'dart:convert';
import 'package:http/http.dart' as http;

class Services {
  static const String url = 'urlllllllllllllllll';

  static Future<List<Post>> getPosts() async {
    try {
      final response = await http.get(Uri.parse(url));
      if (response.statusCode == 200) {
        // 1. 将响应字符串解析为动态数组
        final List<dynamic> jsonList = json.decode(response.body);
        // 2. 遍历数组,把每个元素转为Post实例
        final List<Post> listPosts = jsonList.map((json) => Post.fromJson(json)).toList();
        return listPosts;
      } else {
        return <Post>[];
      }
    } catch (e) {
      print('请求错误: $e');
      return <Post>[];
    }
  }
}

额外说明

  1. 确保Post类的fromJson方法是标准的Map转实例实现,示例如下:
class Post {
  final int id;
  final String title;

  Post({required this.id, required this.title});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      title: json['title'],
    );
  }
}
  1. 如果接口返回的是单个Post对象而非数组,需调整返回类型为Future<Post?>,并修改解析逻辑。

内容的提问来源于stack exchange,提问作者source

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 14:05:21