Flutter & Firebase tips from Toptal Tech Lead and founder of $100K app. Join 2,237+ engineers
Hey Reader, Today I'm gonna show you why I love switch expressions so much. And how you can use them to write clean code. It's time to switch how you write switch. (OK, that was a horrible punch line.) Today we'll cover:
1. What's a switch expression?!Everyone knows this pattern: It works but it's too much code for a simple task. Let's rewrite it using switch expression: Much cleaner. 2. Enum's best friendNow let's say we introduce a new state: loadingLonger, when it's taking more than 5s. Now we'll get an error (which is good!) and compiler will help us handle it. Great. This will only work if there's no default case. So always explicitly write all the cases. IDE or GitHub Copilot will help you with that, so no excuse to be lazy. 3. Sealed classesNow what if Status needed custom data? Let's say a data field for success and message for error. Then we'd use sealed classes, like so: Now each state can have it's own fields. And our switch expression becomes: Great, so we can now have separate cases for each subclass. But what about the custom fields? Well... let's seal the deal. (get it? sealed classes? sorry, here's the code...) So now if status is success, we can safely access it's data field. Pro tip: Use freezed to generate sealed classes (and more). 4. What else can switch do?Let's look at this common production code: Not bad. Well, it's actually quite bad. Let's switch it up: Cool. So we can write and combine conditions, but they all need to be a constant. And I hear you. There's .isEven function. But it's not a constant, so we can't use it as the case pattern. Don't worry - there's guard clause ("when"): That's it. I'm switching off, -Milos P.S. 83 Flutter devs just got early access to my Scalable Flutter App v2. Want it? Then go here to grab it (and save $100). |
Flutter & Firebase tips from Toptal Tech Lead and founder of $100K app. Join 2,237+ engineers