Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to return an anonymous function that returns a widget from a ternary in Dart?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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");}();
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading