2

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?

1
  • Well, for this specific example you could just do if (this._check.type == CheckType.SOME) Text("aaabbb") of course. But I'm assuming you are simplifying the actual problem or not? Commented Sep 20, 2022 at 13:08

4 Answers 4

1

If you want to return a widget in a row widget with an if condition try this :

Row(
   children: [   
       if (this._check.type == CheckType.SOME)...[
           Text("aaa" + "bbb"),
       ],
   ]

)

Sign up to request clarification or add additional context in comments.

2 Comments

But can you add code in [ ] ? The key point is to add some code.
You can't put some variable into [] but you can use this to display a list of widget into an if condition. So if you want to call a function which return a widget with variable you can.
1

The best answer is pretty close to what Ivo said. The answer Ivo gave is correct, but a function is not the best choice, as it will be rebuilt everytime, so you should do something like this:

class CustomTextGetter extends StatelessWidget {
    
    const CustomTextGetter();


    @override
    Widget build(BuildContext context){
        String x="aaa",y="bbb";
        return Text(x+y);
    }

}

Row(
  children: [
    if (this._check.type == CheckType.SOME) const CustomTextGetter(),
    ...
  ]
)

Comments

0

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()
  ]
)

Comments

0
class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return getText("New ext");
  }
  Text getText(String text){
    
    if(true){
       return Text(text);
    }else{
       return Text(text);
    }
   }
}

Created one function getText

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.