Simplify Your Switch Statements
Writing clean and efficient code is crucial for any Flutter developer. Sometimes, you might find yourself writing very similar switch cases for different object types that share common properties. Good news! Dart offers a neat trick to make your code much tidier.
The Power of Logical-Or (||) in Switch Cases
You can use the logical-or pattern (||) to group different object types together in a single switch case. This works great when these object types share the same property names and types, allowing you to handle them uniformly.
Before: Repetitive Switch Cases
Imagine you have a function that needs to count daily statuses from different data types. Without the merge case logic, your code might look a bit repetitive:
int dailyStatusesCount() {
return switch (this) {
TaskRecurrentData(:final dailyStatuses) when dailyStatuses != null => dailyStatuses.length,
HabitTaskWithCounter(:final dailyStatuses) when dailyStatuses != null => dailyStatuses.length,
_ => 0,
};
}
Notice how TaskRecurrentData and HabitTaskWithCounter have very similar logic? We can improve this!
After: Cleaner Code with Merged Cases
Here's how you can simplify it using the logical-or pattern:
int dailyStatusesCount() {
return switch (this) {
TaskRecurrentData(:final dailyStatuses) || HabitTaskWithCounter(:final dailyStatuses)
when dailyStatuses != null => dailyStatuses.length,
_ => 0,
};
}
This makes your code shorter, easier to read, and less prone to errors because you're maintaining logic in one place.
Unified Variable Extraction
A cool feature that comes with this technique is "Unified Variable Extraction." When you use :final dailyStatuses in both patterns, Dart is smart enough to extract the value into a single local variable. This dailyStatuses variable then becomes available for use on the right-hand side of the => in your switch case. This means you don't need to declare dailyStatuses multiple times; Dart handles it for you efficiently.
By adopting advanced merge case logic, you can significantly streamline your Flutter code, making it more maintainable and elegant.