【问题标题】:Dart - How to refactor this loop with copywith?Dart - 如何用 copywith 重构这个循环?
【发布时间】:2023-03-12 05:43:01
【问题描述】:

需要帮助。

假设我有这个列表。

List<Program>
#1: complete = true, currentUuid = null
#2: complete = false, currentUuid = null
#3: complete = false, currentUuid = null
#4: complete = false, currentUuid = null

我的 Program 类是 @immutable 并使用冻结的包(无 setter)。

我需要循环。当我检测到第一个完成 = false 时,我需要为 currentUuid 分配一个值。仅适用于我的示例中的 #2。

#1: complete = true, currentUuid = null
#2: complete = false, currentUuid = '1231232131'
#3: complete = false, currentUuid = null
#4: complete = false, currentUuid = null

我当前的代码有效但臃肿。

List<Program> newPrograms = [];
    
int exitIndex = 0;

for (int i = 0; i < programs.length; i++) {
  if (programs[i].complete) {
    newPrograms.add(programs[i]);
    continue;
  }

  Program newProgram = programs[i].copyWith(currentUuid: programs[i].uuid);
  newPrograms.add(newProgram);
  exitIndex = i;
  break;
}

for (int j = exitIndex + 1; j < programs.length; j++) {
  newPrograms.add(programs[j]);
}

有什么方法可以重构它并制作更好的 dart/flutter 代码?谢谢。

【问题讨论】:

  • 您是否明确不想改变原始programs 列表?如果改变它可以接受,那么你可以只使用一个循环,当它找到你想要的项目时,调用.copyWith,然后调用breaks。
  • @jamesdlin 你能提供一些代码 sn-ps 吗?
  • for (int i = 0; i &lt; programs.length; i++) { if (!programs[i].complete) { programs[i] = programs[i].copyWith(...); break; } }
  • @jamesdlin 感谢分享。

标签: flutter dart


【解决方案1】:

您可以使用indexWhere 获取列表中与您的条件匹配的第一个项目的索引,然后有选择地修改它(或者如果没有找到符合条件的项目,则不更改任何内容)。

// Mutating
final currentIndex = programs.indexWhere((program) => !program.complete);
if (currentIndex >= 0) {
  final temp = programs[currentIndex];
  programs[currentIndex] = temp.copyWith(currentUuid: temp.uuid);
}

// Non-mutating
final newPrograms = List.of(programs);
final currentIndex = newPrograms.indexWhere((program) => !program.complete);
if (currentIndex >= 0) {
  final temp = newPrograms[currentIndex];
  newPrograms[currentIndex] = temp.copyWith(currentUuid: temp.uuid);
}

【讨论】:

  • 感谢您的帮助。学到了一些新东西:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-18
  • 1970-01-01
  • 2023-01-18
相关资源
最近更新 更多