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

Dart控制台应用报错:List<dynamic>不是Map<String, dynamic>的子类型

问题原因

错误List<dynamic> is not a subtype of type Map<String, dynamic>的核心是:你调用的接口返回的是JSON数组格式,但你的Business.fromJson方法是按照单个JSON对象的逻辑来解析的,类型不匹配导致报错。


解决方案

1. 调整接口调用的解析逻辑

直接处理接口返回的数组,将每个数组元素转换为Business对象:

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:marchex_api/clases/business.dart';

void getMarchex(){
    final url = Uri.parse('https://你的实际接口地址');
    http.get(url).then((res){
        // 先将响应体解码为List<dynamic>
        final List<dynamic> jsonArray = json.decode(res.body);
        // 遍历数组,将每个元素转为Business实例
        final List<Business> servicios = jsonArray.map((item) => Business.fromMap(item)).toList();
        print(servicios);
    }).catchError((error)=>print(error));
}

2. (可选)给Business类添加数组解析方法

可以在Business类里新增一个静态方法,专门处理数组格式的JSON:

import 'dart:convert';

class Business {
    // ... 原有类属性和构造函数 ...

    // 新增:解析JSON数组为List<Business>
    static List<Business> fromJsonArray(String jsonStr) {
        final List<dynamic> jsonList = json.decode(jsonStr);
        return jsonList.map((item) => Business.fromMap(item)).toList();
    }

    // ... 原有fromJson、toJson、fromMap、toMap方法 ...
}

调用时就可以简化为:

final List<Business> servicios = Business.fromJsonArray(res.body);

3. 修正Business类的nullable参数问题

原代码里存在矛盾:构造函数中标记为required的参数(比如businessNumber),在fromMap方法里又允许传null,这会导致运行时报错。需要把这些可空参数的定义修正:

class Business {
    Business({
        required this.id,
        required this.businessName,
        this.businessNumber, // 去掉required,改为可选参数
        required this.billableDuration,
        required this.publisherPayout,
        this.businessLatitude,
        this.businessLongitude,
        required this.callTrackingNumber,
        this.businessAddress1,
        this.businessCity,
        this.businessState,
        this.businessZip,
        required this.postbackUrl,
        this.businessShortDescription,
        this.businessLongDescription,
    });

    // 对应的属性也要改为nullable类型
    String id;
    String businessName;
    String? businessNumber;
    String billableDuration;
    String publisherPayout;
    String? businessLatitude;
    String? businessLongitude;
    String callTrackingNumber;
    String? businessAddress1;
    String? businessCity;
    String? businessState;
    String? businessZip;
    String postbackUrl;
    String? businessShortDescription;
    String? businessLongDescription;

    // ... 原有fromJson、toJson、fromMap、toMap方法 ...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:01:14