In Flutter, is there a way to do this:
Widget build(BuildContext context) {
if (someVar != null) {
return WidgetA();
} else {
return WidgetB();
}
}
In a nice syntactically sugary way?
I could try this:
Widget build(BuildContext context) {
return someVar !?? WidgetA() : WidgetB();
}
... but I know it won't work.
You wrote:
Widget build(BuildContext context) {
someVar !?? WidgetA() : WidgetB();
}
It should be ?
and :
for the ternary operator. And in case you don't want to show anything, you can use an empty SizedBox
.
So it could be something like:
Container(
child: _hasName ? Text(name) : SizedBox(),
)
Or if you are writing the build method, don't forget to use the return
keyword:
Widget build(BuildContext context) {
return someVar ? WidgetA() : WidgetB();
}