Flutter IF statements like a Pro

JP
2 min readMar 24, 2024

--

So I’ve been using Flutter & Dart for the last 5 years; I was an early adopter and have never looked back. However one of my biggest frustrations with Dart is with multi-case IF statements.

Consider the following example:

String fruit = "apple";
/// condition check exhaustively one by one
if (number = "pear" || number == "orange" | | number = "apple") {
/// ..

The above approach might look familiar in some situations where you’ll need to exhaustively check for a given case. I’ll admit the above approach looks juvenile; and if I am honest I’d try to avoid it in my code: but sometimes it happens.

Anyways, this kind of IF is troublesome, long, ugly and prone to errors (especially if you have multiple ands / ors. So let’s consider an array based approach:

String fruit = "apple";
/// Check for inclusion in a [List] with .contains() method
if (("pear", "orange", "apple"]).contains(fruit)) {
/// ...

Now the above approach is better because it’s slightly more concise and arguably easier to read. The downside of this approach is that we’ve lost the ability to do ‘Ands’ as well as ‘Ors’ – and some would argue that it is still a little long-hand.

If you know all possible cases (ie if you have an existing array of ‘fruit’ to check against) you could do something this:

String fruit = "apple";
List<String> fruits = ["pear", "orange", "apple"];
/// Check for inclusion in a [List] with .contains() method
if (fruits.contains(fruit)) {
/// ...

This approach is perhaps the ‘shortest’ but you do introduce a new array variable to your scope. From a readability perspective you are also making it harder to understand what the IF statement is comparing against as the cases are encapsulated within the array which might have been defined out of sight elsewhere in your codebase. This adds technical debt to your codebase.

Finally, for all Dart 3 users, this is my absolute new favourite way to handle this use case:

String fruit = "apple";
/// Ise Dart 3’s new ‘case’ syntax
if (fruit case "pear" || "orange" || "apple") {
/// ...

The use of ‘case’ makes this kind of IF statement short and concise whilst also being super easy to read and understand at a glance. Again as with all three methods proposed, there are small amounts of tech-debt to consider, but if this situation came up in my code, I know which approach I’ll be taking.

So there you go! Three different approaches to IF statements for your usage. Have a different approach – let me know in the comments and I’ll update this article!

--

--

JP

Senior Flutter & SwiftUI App Dev; owner of HyperPixel.co.uk; business founder & tech-educator. I help create mobile experiences and teach others how to too.