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

Flutter调用WordPress REST API报错:List<dynamic>无法转为Map<String, dynamic>

解决Flutter解析WordPress REST API分类数据时的类型不匹配错误

错误原因

WordPress REST API的/wp/v2/categories接口返回的是多个分类对象组成的数组(List<dynamic>),但你的CategoriesResponse模型仅支持解析单个分类对象(Map<String, dynamic>),直接用单个对象的解析逻辑处理数组,就会抛出type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'错误。

解决方案

1. 调整模型类(适配数组解析)

将原模型类重命名为Category(对应单个分类条目),并添加数组解析方法:

import 'dart:convert';

class Category {
  Category({
    required this.id,
    required this.count,
    required this.description,
    required this.name,
  });

  int id;
  int count;
  String description;
  String name;

  factory Category.fromJson(String str) => Category.fromMap(json.decode(str));
  
  // 新增:从API返回的数组字符串解析成分类列表
  static List<Category> fromJsonList(String str) {
    final List<dynamic> categoryList = json.decode(str);
    return categoryList.map((item) => Category.fromMap(item)).toList();
  }

  String toJson() => json.encode(toMap());

  factory Category.fromMap(Map<String, dynamic> json) => Category(
        id: json["id"],
        count: json["count"],
        description: json["description"],
        name: json["name"],
      );

  Map<String, dynamic> toMap() => {
        "id": id,
        "count": count,
        "description": description,
        "name": name,
      };
}

2. 修改Provider中的数据解析逻辑

更新getCategories方法,将API响应解析为分类列表:

class CategoriesProvider extends ChangeNotifier {
  String _baseUrl = 'webpage.net';
  String _fields = 'id,count,description,name,link';
  // 新增:用于存储分类列表
  List<Category> _categories = [];
  List<Category> get categories => _categories;

  CategoriesProvider() {
    getCategories();
  }

  getCategories() async {
    var url =
        Uri.https(_baseUrl, 'wp-json/wp/v2/categories', {'_fields': _fields});

    final response =
        await http.get(url, headers: {"Accept": "application/json"});

    // 解析成分类列表
    _categories = Category.fromJsonList(response.body);
    
    // 示例:打印第一个分类的count(需判断列表非空)
    if (_categories.isNotEmpty) {
      print(_categories.first.count);
    }
    
    // 通知UI更新
    notifyListeners();
  }
}

关键说明

  • API返回结构验证:可以先打印response.body确认格式,分类接口返回的是[ {...}, {...} ]形式的数组,而非单个对象
  • 语义化命名:将模型类改为Category更贴合实际含义,避免混淆单个条目和列表

内容的提问来源于stack exchange,提问作者Miguel Álvarez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:35:16