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

Flutter中父类内WorkoutExercise列表反序列化问题求助

解决Flutter中父类对象列表的反序列化问题

你的问题核心在于:直接将snapshot['e']强制转换为List<WorkoutExercise>是无效的,因为从Map中取出的'e'对应的是一组**Map<String, dynamic>类型的元素**,而非已实例化的WorkoutExercise对象。

修正后的代码

假设WorkoutExercise类已经实现了自己的fromMap构造函数(比如WorkoutExercise.fromMap(Map<String, dynamic> map)),修改Workout.fromMap的最后一行即可:

class Workout {
  String uid;
  String id;
  String name;
  String folderid;
  int order = 0;
  List<WorkoutExercise> workoutExercises = [];

  Workout({
    required this.uid,
    required this.id,
    required this.name,
    required this.folderid,
    required this.workoutExercises,
  });


  Workout.fromMap(Map<String, dynamic> snapshot, this.uid)
      : name = snapshot['n'] as String,
        id = snapshot['i'] as String,
        folderid = snapshot['f'] as String,
        order = snapshot['o'] as int,
        workoutExercises = (snapshot['e'] as List<dynamic>)
            .map((exerciseMap) => WorkoutExercise.fromMap(exerciseMap))
            .toList();
}

关键说明

  1. 先将snapshot['e']转换为List<dynamic>,确保能遍历其中的每个元素
  2. 通过map方法遍历每个元素,调用WorkoutExercise.fromMap将单个Map转换为WorkoutExercise对象
  3. 最后用toList()将Iterable转换为List<WorkoutExercise>

如果WorkoutExercise还没有fromMap构造函数,你需要先实现它,示例如下:

class WorkoutExercise {
  // 假设你的WorkoutExercise有这些字段
  String id;
  String name;
  int sets;

  WorkoutExercise({required this.id, required this.name, required this.sets});

  WorkoutExercise.fromMap(Map<String, dynamic> map)
      : id = map['id'] as String,
        name = map['name'] as String,
        sets = map['sets'] as int;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 11:06:04