Skip to content

Instantly share code, notes, and snippets.

@crizant
Created February 7, 2020 17:27
Show Gist options
  • Save crizant/d6b4230e81bc50e63f04d0a0e6172e64 to your computer and use it in GitHub Desktop.
Save crizant/d6b4230e81bc50e63f04d0a0e6172e64 to your computer and use it in GitHub Desktop.
Flutter conditional rendering - good practice
// 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