Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Weird behaviour of ternary Operator with cascade dart

Why do both of the results print the same?

final list1 = [ "a", "b", "c" ];
final result1 = true ? list1 : list1..removeWhere((e) => e == "a");
print(result1); // prints ["b", "c"]

final list2 = [ "a", "b", "c" ];
final result2 = false ? list2 : list2..removeWhere((e) => e == "a");
print(result2); // prints ["b", "c"]

This happens only in ternary condition. When in normal if-else this works just fine.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The ternary operator is evaluated before the cascade operator, so basically the code is equivalent to

final result1 = (true ? list1 : list1)..removeWhere((e) => e == "a");

rather than what you might have expected

final result1 = true ? list1 : (list1..removeWhere((e) => e == "a"));

See: Operator precedence

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading