Flutter - How to show view according to condition base

During the app devlopment, sometimes we need to show view according to condition base using if..else statement. But in Flutter, we can’t use if…else statement directly on child view because it accepts only widgets. But we can use conditions child view like below example.

1: Using Conditional Operators (? :) also say Ternary Operator :

bool isLoading = true;

Center( 
    child: isLoading? //check if isLoading is true or false
       CircularProgressIndicator(valueColor:AlwaysStoppedAnimation<Color>( Colors.pink)),: //show progress when isLoading= true
       Text("Errorgram"), //show this text when isLoading= false
)
 
Using Multiple Conditions :
 
bool isLoading = true;
bool isError = true;

Center( 
    child: isLoading? //check if isLoading is true or false
       CircularProgressIndicator(valueColor:AlwaysStoppedAnimation<Color>( Colors.pink)),: //show progress when isLoading = true
       isError?Text("It's Error"): //when isLoading = false, and then check isError is true or false
                  Text("No Error"), //if isLoading = false and isError= false, then show this text //show text when isLoading = false
)

2: Using  IF....ELSE like below on Children view :

Wec can use this conditional statement on widget tree which has "children" property, for example, Column(), Row() and Wrap() widgets like below.

Column(
  children: [ 
    if(true)...[
      Text("It's true..."),
    ]else...[
      Text("It's false...")
    ]
])

 

3: Usin Conditions (IF... ELSE) on Builder : 

Now, we are going to use if else statement with LayoutBuilder

Container(
    child:LayoutBuilder(builder: (context, constraints) { 
        if(true){
            return Text("It's true...");
        }else{
            return Text("It's false...");
        }  
    })
)

I  hope you like this article and it will be help to you.

Tags: