Created
February 7, 2020 17:27
-
-
Save crizant/d6b4230e81bc50e63f04d0a0e6172e64 to your computer and use it in GitHub Desktop.
Flutter conditional rendering - good 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
// Good | |
class MyWidget extends StatelessWidget { | |
final List<int> numbers = []; | |
@override | |
Widget build(BuildContext context) { | |
return Container( | |
child: Conditional.single( | |
context: context, | |
conditionBuilder: (BuildContext context) { | |
// These lines live inside the condition builder only. | |
final int firstEvenNumber = numbers.firstWhere( | |
(element) => element % 2 == 0, | |
orElse: () => null, | |
); | |
return firstEvenNumber != null; | |
}, | |
widgetBuilder: (BuildContext context) { | |
// the widget is created only when we need to render it, | |
// while maintaining good readability. | |
return Text( | |
'Even number found.', | |
style: TextStyle( | |
color: Colors.green, | |
), | |
); | |
}, | |
fallbackBuilder: (BuildContext context) { | |
return Text( | |
'There is no even numbers.', | |
style: TextStyle( | |
color: Colors.red, | |
), | |
); | |
} | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment