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):
Here is the solution. I have fixed it. Here is the code
child: _status(data[index]["status"]),
Widget _status(status) {
if (status == "3") {
return Text('Process');
} else if(status == "1") {
return Text('Order');
} else {
return Text("Waiting");
}
}
In my app I created a WidgetChooser
widget so I can choose between widgets without conditional logic:
WidgetChooser(
condition: true,
trueChild: Text('This widget appears if the condition is true.'),
falseChild: Text('This widget appears if the condition is false.'),
);
This is the source for the WidgetChooser
widget:
import 'package:flutter/widgets.dart';
class WidgetChooser extends StatelessWidget {
final bool condition;
final Widget trueChild;
final Widget falseChild;
WidgetChooser({@required this.condition, @required this.trueChild, @required this.falseChild});
@override
Widget build(BuildContext context) {
if (condition) {
return trueChild;
} else {
return falseChild;
}
}
}
Only if vibrating widget
if(bool = true) Container(
child: ....
),
OR
if(bool = true) Container(
child: ....
) else new Container(child: lalala),
Lol after months of using ?: I just find out that I can use this:
Column(
children: [
if (true) Text('true') else Text('false'),
],
)
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.
With a button
bool _paused = false;
CupertinoButton(
child: _paused ? Text('Play') : Text('Pause'),
color: Colors.blue,
onPressed: () {
setState(() {
_paused = !_paused;
});
},
),