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

Flutter GetX调用Jikan API报错:_Map<String,dynamic>非String子类型

Flutter+GetX调用Jikan动漫API类型不匹配问题修复指导

问题说明

调用Jikan动漫API(https://api.jikan.moe/v4/anime)时触发类型转换错误:type '_Map<String, dynamic>' is not a subtype of type 'String'

相关代码

anime_api_server.dart

Future<List<Datum>> fetchAnimeData() async {
    final response =
        await http.get(Uri.parse('https://api.jikan.moe/v4/anime'));
    if (response.statusCode == 200) {
      final List result = jsonDecode(response.body)['data'];
      final List<Datum> respoList =
          result.map((json) => Datum.fromJson(json)).toList();
      return respoList;
    } else {
      throw Exception('Failed to load anime data');
    }
  }

anime_controller.dart

AnimeServer apiService = AnimeServer();
  var isLoading = false.obs;
  var animedataList = <Datum>[].obs;

  @override
  void onInit() {
    fetchAnimeData();
    super.onInit();
  }

  void fetchAnimeData() async {
    try {
      isLoading(true);

      final List<Datum> animeList = await apiService.fetchAnimeData();

      animedataList.addAll(animeList);
    } catch (e) {
      print("Error: ${e.toString()}");
    } finally {
      isLoading(false);
    }
  }

调试日志

Restarted application in 5,852ms.
[GETX] Instance "GetMaterialController" has been created

[GETX] Instance "GetMaterialController" has been initialized

[GETX] Instance "AnimeController" has been created

[GETX] Instance "AnimeController" has been initialized

I/flutter (10968): Error: type '_Map<String, dynamic>' is not a subtype of type 'String'

问题原因及修复方案

错误核心是Datum模型类的字段类型与API返回的JSON结构不匹配:API返回的部分字段是嵌套Map结构,但你的Datum类中对应字段被定义为String类型,导致解析时类型转换失败。

具体修复步骤:

  1. 核对Datum类与API返回结构

    • 直接访问https://api.jikan.moe/v4/anime查看返回的JSON数据,逐一对比Datum类的每个字段类型。
    • 比如API中的images、trailer、aired都是嵌套Map,若Datum类中把这些字段定义为String,就会触发错误。
  2. 修正Datum类的字段类型

    • 对于嵌套结构,要么定义对应的子模型类(比如ImageModel),要么将字段类型改为Map<String, dynamic>。
    • 示例:
      // 错误写法
      String images;
      // 正确写法1:用子模型类
      ImageModel images;
      // 正确写法2:直接存Map
      Map<String, dynamic> images;
      
  3. 调整fromJson解析逻辑

    • 手动解析时,要对嵌套Map做对应处理:
      // 解析子模型
      ImageModel.fromJson(json['images']);
      // 或直接提取嵌套中的字符串字段
      json['images']['jpg']['image_url'] as String;
      
    • 若使用json_serializable库,需确保子模型类也添加@JsonSerializable()注解并生成解析方法。
  4. 快速定位问题字段

    • 在fetchAnimeData中添加打印语句,查看单条数据结构:
      print(result.first);
      
      通过输出内容快速找到哪个字段是Map类型,再针对性修正。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 02:42:41