How to simplify if expression with code that returns Widget in Flutter?

Issue

This is my code:

   Row(
    children: [   
      if (this._check.type == CheckType.SOME)((){
         var a = "aaa"; 
         var b = "bbb"
         return Text(a + b);
      }()),
    ]
   )

This code works and does what I need, however, I would like to simplify it. I tried:

   Row(
    children: [   
      if (this._check.type == CheckType.SOME) {
         var a = "aaa"; 
         var b = "bbb"
         return Text(a + b);
      },
    ]
   )

but it doesn’t work. Is there any syntax construction to simplify if condition with code in Widget?

Solution

You could extract the code for making that portion to a function, like this for example

Text getText() {
  var a = "aaa";
  var b = "bbb";
  return Text(a + b);
}

And use it like

Row(
  children: [
    if (this._check.type == CheckType.SOME) getText()
  ]
)

Answered By – Ivo

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *