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

Flutter如何实现可选序列化列表或单个对象数据?

解决Flutter中类似DRF的多/单对象序列化问题

问题分析

你的代码存在几个核心问题:

  • UserProfileSeralizer.fromJson是工厂构造方法,属于静态上下文,无法直接访问类的实例变量many
  • data变量在if/else代码块内定义,外部无法访问,导致返回时找不到该变量
  • 构造函数的参数顺序和返回时的传参不匹配(many是位置参数,但返回时用了命名参数传递)

修正后的代码

class Data {
  final int? id;
  final String? avatar;

  Data({
    required this.id,
    required this.avatar,
  });

  factory Data.fromJson(Map<String, dynamic> json) {
    return Data(
      id: json['id'],
      avatar: json['avatar'],
    );
  }
}

class UserProfileSerializer {
  final String? message;
  final int? statusCode;
  final dynamic data;
  final bool many;

  // 调整构造函数,将many改为命名参数,与其他参数统一
  UserProfileSerializer({
    required this.many,
    this.message,
    this.statusCode,
    this.data,
  });

  // 给fromJson添加many参数,让调用者指定解析列表还是单个对象
  factory UserProfileSerializer.fromJson(Map<String, dynamic> json, {bool many = true}) {
    final message = json['message'];
    final statusCode = json['statusCode'];
    final tempDataJson = json['data'];
    
    dynamic data;
    if (many) {
      // 将列表中每个JSON对象解析为Data实例
      data = (tempDataJson as List).map((item) => Data.fromJson(item)).toList();
    } else {
      // 直接解析单个JSON对象为Data实例
      data = Data.fromJson(tempDataJson);
    }

    return UserProfileSerializer(
      many: many,
      message: message,
      statusCode: statusCode,
      data: data,
    );
  }
}

使用示例

// 解析列表形式的API返回
final listResponse = UserProfileSerializer.fromJson(jsonData, many: true);
List<Data>? userList = listResponse.data as List<Data>?;

// 解析单个对象形式的API返回
final singleResponse = UserProfileSerializer.fromJson(jsonData, many: false);
Data? user = singleResponse.data as Data?;

关键改动说明

  1. 给fromJson添加many参数:让调用者在解析时明确指定处理类型,替代原来的实例变量方式,解决静态上下文无法访问实例变量的问题
  2. 调整构造函数参数:将many改为命名参数,避免位置参数与命名参数混用导致的错误
  3. 修复变量作用域:在if/else外部定义data变量,确保返回时能正常访问
  4. 完善列表解析逻辑:原来仅将数据转为List,现在通过map把每个元素解析为Data实例,完成真正的序列化

内容的提问来源于stack exchange,提问作者Alif Irhas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 05:16:08