Skip to content

Instantly share code, notes, and snippets.

@crizant
Last active February 7, 2020 17:26
Show Gist options
  • Save crizant/811a7abb3270d06428b56e12e2b4ca96 to your computer and use it in GitHub Desktop.
Save crizant/811a7abb3270d06428b56e12e2b4ca96 to your computer and use it in GitHub Desktop.
Flutter conditional rendering - bad practice
// 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