Jonas
Jonas

Reputation: 7915

Shorter way to write this conditional statement?

Is there a better alternative then coding this:

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

I could also do this:

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

But this way it's not one line and it's not a condition so I could use it in a Text()constructor.

Upvotes: 1

Views: 68

Answers (1)

Rémi Rousselet
Rémi Rousselet

Reputation: 277477

You can use ?. and ?? operators:

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

Upvotes: 7

Related Questions