编写此条件语句的更短方法?

时间:2019-02-21 20:31:17

标签: dart flutter

有没有比这更好的替代方法了?

String reps = status != null && status.sets != null && status.sets[index].reps != null ? status.sets[index].reps.toString() : '-';

我也可以这样做:

String reps;
try {
  reps = hasImprovedReps ? currentReps : status.sets[index].reps.toString();
} catch (e) {
  reps = '-';
}

但是这种方式不是一行,也不是条件,因此我可以在Text()构造函数中使用它。

1 个答案:

答案 0 :(得分:6)

您可以使用?.??运算符:

String reps = status?.sets?.elementAt(index)?.reps?.toString() ?? '-'