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

Question

Asked by Pavel_K on September 20, 2022 (source).

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?

Answer

Question answered by Ivo (source).

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()
  ]
)
DART FLUTTER
SHARE: