So far whenever I needed to use a conditional statement within a Widget I have done the following (Using Center and Containers as simplified dummy examples):
In flutter if you want to do conditional rendering, you may do this:
Column(
children: [
if (isCondition == true)
Text('The condition is true'),
],
);
But what if you want to use a tertiary (if-else) condition? when the child widget is multi-layered.
You can use this for its solution flutter_conditional_rendering a flutter package which enhances conditional rendering, supports if-else and switch conditions.
If-Else condition:
Column(
children: [
Conditional.single(
context: context,
conditionBuilder: (BuildContext context) => someCondition == true,
widgetBuilder: (BuildContext context) => Text('The condition is true!'),
fallbackBuilder: (BuildContext context) => Text('The condition is false!'),
),
],
);
Switch condition:
Column(
children: [
ConditionalSwitch.single(
context: context,
valueBuilder: (BuildContext context) => 'A',
caseBuilders: {
'A': (BuildContext context) => Text('The value is A!'),
'B': (BuildContext context) => Text('The value is B!'),
},
fallbackBuilder: (BuildContext context) => Text('None of the cases matched!'),
),
],
);
If you want to conditionally render a list of widgets (List
instead of a single one. Use Conditional.list()
and ConditionalSwitch.list()!