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):
The other answers don't mention it, you may also:
The Builder widget is meant for allowing the use of a closure when a child widget is required:
A platonic widget that calls a closure to obtain its child widget.
It is convenient anytime you need logic to build a widget, it avoids the need to create a dedicated function. Also i find it makes what's being done clearer compared to using an immediate anonymous function.
You use the Builder widget as the child and provide your logic in its builder method. With your example it goes:
Center(
child: Builder(
builder: (context) {
if (condition) {
return Container();
} else {
return Center();
}
}
)
)
In such a trivial example the ternary operator would suffice (child: condition ? Container() : Center()), but if more logic is needed, the Builder provides a convenient place to hold it.
Also I agree with other posters that the logic should be extracted from the UI code, but when it's only a switch or if/else statement used to determine the widget to build, I prefer to keep it there (provided the condition is simple, for example testing a value in a ViewModel). The Builder widget can help in this.