首页 > 解决方案 > 使用来自 id 的对象填充冻结模型

问题描述


sembast用来将模型存储在本地存储中的上下文。这里的逻辑是,每个Sprint都会有 5 个Day对象。Sprint我没有将整个对象存储在对象中,而是存储这些Day对象的 ID。请记住,所有SprintDay都将分别存储在本地存储中sprintday存储中。

问题 我想使用存储Task的对象访问对象。这就是为什么,我想用对象填充对象。SprinttaskIdsSprintTask

我有一个Sprint具有以下结构的冻结模型:

@freezed
class Sprint with _$Sprint {
  factory Sprint({
    required String id,
    required String title,
    required DateTime startDateTime,
    required List<String> dayIds,
  }) = _Sprint;

factory Sprint.fromJson(Map<String, dynamic> json) => 
_$SprintFromJson(json);
}

和一个Day结构模型:

@freezed
class Day with _$Day {
  factory Day({
    required String id,
    required DateTime dateTime,
  }) = _Day;

factory Day.fromJson(Map<String, dynamic> json) => 
_$DayFromJson(json);
}

days在加载视图模型时使用变量的方法

List<Day> days = []

Future<void> onModelReady() async {
  for(final dayId in currentSprint.dayIds) {
    days.add(await _dayController.fetchDayById(dayId))
  }
}

// use `days` variable

populateWithDays但是我认为它添加了丰富的代码,如果对象上有方法可以防止Sprint,可以在方法中调用onModelReady

Future<void> onModelReady() async {
  await currentSprint.populateWithDays();
}

void useDays() {
  for(final day in sprint.days) { // here `days` is different than `dayIds` 
    print(day.dateTime);
  }
}

我可以通过修改Sprint模型来保存与in属性Day关联的 s 对象列表,当被调用时。但我不想将和存储在同一个对象中。dayIdsdayspopulateWithDaysdayIdsdays

标签: flutterdartflutter-freezed

解决方案


推荐阅读