skip to Main Content

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


  1. You can use an anonymous function by actually executing it also by following it by (), so for example this is possible:

      Widget test(bool condition) {
        return condition ? Text("") : (){print('yes'); return Text("Hello");}();
      }
    
    Login or Signup to reply.
  2. While it is entirely possible to implement this in the build function of a StatelessWidget 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 the condition, or better yet, use a state management approach separate from the widget tree to handle it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search