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

Flutter模型中<String, Object>类型Map及List的fromJson()处理咨询

Flutter模型中Map<String, Object>与List类型的fromJson实现

一、Map<String, Object>类型的处理

假设你的模型类包含一个Map<String, Object>类型字段,以下是标准实现示例:

class UserModel {
  final String id;
  final String name;
  final Map<String, Object>? extraInfo; // 可空Map字段

  UserModel({
    required this.id,
    required this.name,
    this.extraInfo,
  });

  factory UserModel.fromJson(Map<String, dynamic> json) {
    return UserModel(
      id: json['id'] as String,
      name: json['name'] as String,
      // 处理可空场景,直接强转Map类型
      extraInfo: json['extraInfo'] == null 
          ? null 
          : json['extraInfo'] as Map<String, Object>,
    );
  }
}

如果字段不可空且后端必然返回该字段,可简化为:

extraInfo: json['extraInfo'] as Map<String, Object>,

若后端返回的字段类型不稳定(比如偶尔返回非Map值),可增加类型校验避免崩溃:

extraInfo: json['extraInfo'] is Map 
    ? json['extraInfo'] as Map<String, Object>
    : {}, // 或返回null,根据业务需求调整

二、List类型的处理

List类型分两种场景处理:基础类型List和自定义模型List。

1. 基础类型List(如List、List)

示例模型包含List<String>标签字段:

class ProductModel {
  final String productId;
  final List<String> tags;

  ProductModel({
    required this.productId,
    required this.tags,
  });

  factory ProductModel.fromJson(Map<String, dynamic> json) {
    return ProductModel(
      productId: json['productId'] as String,
      // 将动态List转为指定基础类型List
      tags: (json['tags'] as List).cast<String>(),
    );
  }
}

可空List的处理方式:

final List<String>? tags;

// fromJson中
tags: json['tags'] == null 
    ? null 
    : (json['tags'] as List).cast<String>(),

2. 自定义模型List(如List)

先定义子模型:

class OrderItem {
  final String itemId;
  final double price;

  OrderItem({
    required this.itemId,
    required this.price,
  });

  factory OrderItem.fromJson(Map<String, dynamic> json) {
    return OrderItem(
      itemId: json['itemId'] as String,
      price: (json['price'] as num).toDouble(),
    );
  }
}

主模型中解析List:

class OrderModel {
  final String orderId;
  final List<OrderItem> items;

  OrderModel({
    required this.orderId,
    required this.items,
  });

  factory OrderModel.fromJson(Map<String, dynamic> json) {
    return OrderModel(
      orderId: json['orderId'] as String,
      // 遍历元素并调用子模型的fromJson方法
      items: (json['items'] as List)
          .map((itemJson) => OrderItem.fromJson(itemJson))
          .toList(),
    );
  }
}

可空自定义模型List的处理:

final List<OrderItem>? items;

// fromJson中
items: json['items'] == null 
    ? null 
    : (json['items'] as List)
        .map((itemJson) => OrderItem.fromJson(itemJson))
        .toList(),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 14:45:40