How to use Conditional Statement (IF ELSE) on Child Widget in Flutter

During building an app, sometimes we need to show content according to condition using if..else statement. But in Flutter, we can’t place if…else statement directly on child attribute because it accepts only widgets. But you can apply conditions child attribute like shown in the example below.

Method 1: Using Conditional Operators (? :) called Ternary Operator:

bool loading = true;
Container( 
    child: loading? //check if loading is true or false
        CircularProgressIndicator(): //show progress on loading = true
        Text("Loaded"), //show this text on loading = false
)

Using Multiple Conditions:

bool loading = false;
bool error = true;
Container( 
    child: loading? //first check if loading is true or false
            CircularProgressIndicator(): //show progress on loading = true
                error?Text("Error"): //when loading = false, and then check error is true or false
                  Text("Loaded and No Error"), //if loading = false and error = false, then show this text
)

Another Example:

int y = 5;
Container( 
    child: y >= 10?
           Text("Y is greater than or equal to 10"):
           Text("Y is less than 10")
)

Method 2: Apply Conditions (IF... ELSE) on LayoutBuilder:

int y = 5;
Container(
    child:LayoutBuilder(builder: (context, constraints) { 
        if(y >= 10){
            return Text("Y is greater than or equal to 10");
        }else{
            return Text("Y is less than 10");
        }  
    })
)

Method 3: Using another Method/Function:

class _MyAppState extends State<MyApp> {
  int y = 5;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
          body: showwidget()
      );
  }

  showwidget(){
     if(y >= 10){
        return Text("Y is greater than or equal to 10");
     }else{
        return Text("Y is less than 10");
     }
  }
}

In this way, you can use conditional statements, comparisons in child property, or on any widget in Flutter. 

No any Comments on this Article


Please Wait...