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

Flutter中List<dynamic>无法转为List<InvoiceItemDto>?的异常求助

问题解决步骤

1. 修复List类型转换异常

Dart中map方法默认返回Iterable<dynamic>,直接调用toList()得到的是List<dynamic>,无法直接匹配List<InvoiceItemDto>?类型。可以通过两种方式显式指定类型:

方式一:泛型List构造器

invoiceItems: json['invoiceItems'] != null
    ? List<InvoiceItemDto>.from(
        json['invoiceItems'].map((data) => InvoiceItemDto.fromJson(data)),
      )
    : null,

方式二:类型转换+泛型map

invoiceItems: (json['invoiceItems'] as List<dynamic>)
    .map<InvoiceItemDto>((data) => InvoiceItemDto.fromJson(data))
    .toList() as List<InvoiceItemDto>?,

2. 修复InvoiceItemDto.fromJson的逻辑错误

你的fromJson方法存在两处数据解析错误,会导致字段值异常:

  • id类型不匹配:JSON中的id是字符串格式(如"13"),但Dto的id是int?类型,需要转换为整数
  • description字段取值错误:JSON中字段名为description,但代码里错误取了json['address'],会导致description始终为null

修正后的fromJson方法:

factory InvoiceItemDto.fromJson(Map<String, dynamic> json) {
  return InvoiceItemDto(
    id: json['id'] != null ? int.parse(json['id']) : null,
    description: json['description'],
  );
}

3. 完整解析示例

假设你在父级Dto中解析invoiceItems,完整代码示例如下:

class InvoiceDto {
  final List<InvoiceItemDto>? invoiceItems;

  InvoiceDto({this.invoiceItems});

  factory InvoiceDto.fromJson(Map<String, dynamic> json) {
    return InvoiceDto(
      invoiceItems: json['invoiceItems'] != null
          ? List<InvoiceItemDto>.from(
              json['invoiceItems'].map((data) => InvoiceItemDto.fromJson(data)),
            )
          : null,
    );
  }
}

class InvoiceItemDto {
  final int? id;
  final String? description;    

  const InvoiceItemDto({
   this.id,
   this.description,
  });

  factory InvoiceItemDto.fromJson(Map<String, dynamic> json) {
    return InvoiceItemDto(
      id: json['id'] != null ? int.parse(json['id']) : null,
      description: json['description'],
    );
  }

  InvoiceItemEntity toInvoiceItemEntity() {
    return InvoiceItemEntity(id: id, description: description);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:08:20