In Flutter the pattern of using a ternary to conditionally return a widget is common. However I also find myself wanting to be able to run logic before returning a widget on one side of the evaluation.
Something like
condition ? Text("") : (){... some logic; return Text("Hello")}
However it seems this isn’t possible with Dart’s syntax, or I can’t figure out how to do it.
I know the Builder widget can be used in this scenario but it seems overkill to use an entire Builder widget just to do this
2
Answers
You can use an anonymous function by actually executing it also by following it by
()
, so for example this is possible:While it is entirely possible to implement this in the
build
function of aStatelessWidget
in Flutter, as shown in Ivo’s answer, it is also highly problematic.You have absolutely no control over when or how often your logic code will be executed. The Flutter framework may run the build process at any time, and any number of times for your widget tree or part of it.
Maybe you should consider using a
StatefulWidget
to have control over when to evaluate thecondition
, or better yet, use a state management approach separate from the widget tree to handle it.