Last active
February 7, 2020 17:26
-
-
Save crizant/811a7abb3270d06428b56e12e2b4ca96 to your computer and use it in GitHub Desktop.
Flutter conditional rendering - bad practice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Bad | |
class MyWidget extends StatelessWidget { | |
final List<int> numbers = []; | |
@override | |
Widget build(BuildContext context) { | |
// These lines only related to the condition, | |
// but they are at the topmost scope of the `build` function. | |
final int firstEvenNumber = numbers.firstWhere( | |
(element) => element % 2 == 0, | |
orElse: () => null, | |
); | |
// For illustration purpose I put simple widgets here. | |
// But you can imagine how bad the readability will be, | |
// when the widget is more complex. | |
final Widget widgetToRender = firstEvenNumber != null | |
? Text( | |
'Even number found.', | |
style: TextStyle( | |
color: Colors.green, | |
), | |
) | |
: Text( | |
'There is no even numbers.', | |
style: TextStyle( | |
color: Colors.red, | |
), | |
); | |
return Container( | |
child: widgetToRender, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment