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

Flutter新手求助:基于模型类将API响应转为三个Map

解决思路与实现示例

1. 先明确模型与API响应结构(基于常见场景假设)

假设你的NotificationSetup模型大致结构如下(如果和你的实际结构有出入,调整字段即可):

class NotificationSetup {
  final Sms sms;
  final Email email; // 对应邮件配置的模型类
  final MobilePush mobile; // 对应移动端推送的模型类

  NotificationSetup({required this.sms, required this.email, required this.mobile});

  // 你已经实现的JSON解析构造函数
  factory NotificationSetup.fromJson(Map<String, dynamic> json) {
    return NotificationSetup(
      sms: Sms.fromJson(json['sms']),
      email: Email.fromJson(json['email']),
      mobile: MobilePush.fromJson(json['mobile']),
    );
  }
}

class Sms {
  final bool enabled;
  final List<String> notificationTypes;

  Sms({required this.enabled, required this.notificationTypes});

  factory Sms.fromJson(Map<String, dynamic> json) {
    return Sms(
      enabled: json['enabled'],
      notificationTypes: List<String>.from(json['notification_types']),
    );
  }
}

// Email、MobilePush模型结构与Sms类似,自行补充字段即可

2. 从模型提取生成三个独立Map

有两种简单的实现方式,按需选择:

方法一:给子模型添加toMap()方法

直接在Sms、Email、MobilePush类中添加转换方法,把模型字段转成Map:

class Sms {
  // ... 原有字段和构造函数

  Map<String, dynamic> toMap() {
    return {
      'enabled': enabled,
      'notification_types': notificationTypes,
      // 补充你需要导出的其他字段
    };
  }
}

// Email和MobilePush类同理添加toMap()方法

使用时直接调用即可生成独立Map:

// 假设你已经解析好的NotificationSetup实例
final notificationSetup = NotificationSetup.fromJson(apiResponse);

final smsMap = notificationSetup.sms.toMap();
final emailMap = notificationSetup.email.toMap();
final mobileMap = notificationSetup.mobile.toMap();

方法二:单独写工具转换函数(不修改现有模型)

如果不想改动已有的模型类,写单独的工具函数处理:

Map<String, dynamic> convertSmsToMap(Sms sms) {
  return {
    'enabled': sms.enabled,
    'notification_types': sms.notificationTypes,
    // 补充其他需要的字段
  };
}

// 同理编写convertEmailToMap、convertMobileToMap函数

// 使用示例:
final smsMap = convertSmsToMap(notificationSetup.sms);
final emailMap = convertEmailToMap(notificationSetup.email);
final mobileMap = convertMobileToMap(notificationSetup.mobile);

3. 特殊场景处理:平级API响应拆分

如果API返回的是平级字段(比如用sms_enabled、email_enabled这类前缀区分),可以通过字段过滤拆分:

// 示例平级API响应
final apiResponse = {
  'sms_enabled': true,
  'sms_notification_types': ['order', 'alert'],
  'email_enabled': false,
  'email_notification_types': ['promo'],
  'mobile_enabled': true,
  'mobile_notification_types': ['all'],
};

// 提取sms相关字段并去掉前缀
final smsMap = apiResponse.entries
    .where((entry) => entry.key.startsWith('sms_'))
    .map((entry) => MapEntry(entry.key.replaceFirst('sms_', ''), entry.value))
    .toMap();

// 用同样逻辑处理email和mobile字段

内容的提问来源于stack exchange,提问作者Muhammed Ajmal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:05:24