Home > Back-end >  How to simplify if expression with code that returns Widget in Flutter?
How to simplify if expression with code that returns Widget in Flutter?

Time:09-21

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?

CodePudding user response:

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"),
       ],
   ]

)

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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