Debug School

rakesh kumar
rakesh kumar

Posted on

How to use Conditional statement in widget in flutter?

Using the ternary operator

Using If Statement.

Using a method.

Using the switch statement

ternary operator on networkImage

If statement on networkImage

switch statement on Month

ternary operator on Loading

ternary operator on Loading using multiple condition

IF....ELSE like below on Children property:

IF... ELSE on LayoutBuilder:

IF... ELSE on Using another Method/Function:

click here
click here
flutter-use-conditional-statement-in-child-widget

Using the ternary operator

I think Easiest method to use Conditional statement in widget in flutter is By Using the ternary operator. Its as simple as possible. Lets see Quick Example Here.

Suppose we have a variable named networkImage. We want if networkImage is null then view Assets Image else view networkImage. Here we are going to use Ternary Operators.

 Container(
              height: 200,
              width: 200,
              child: networkImage != null
                  ? Image(
                      image: NetworkImage(
                        networkImage,
                      ),
                    )
                  : Image(
                      image: AssetImage('assets/asset_img.jpeg'),
                    ),
            ),
Enter fullscreen mode Exit fullscreen mode

Image description

Using If Statement

I personally use if/else statement in children with this kind of block statement. It only supports on Dart version 2.3.0 above

child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            if (networkImage == null) ...[
              Container(
                height: 200,
                width: 200,
                child: Image(
                  image: AssetImage('assets/asset_img.jpeg'),
                ),
              ),
            ] else ...[
              Container(
                height: 200,
                width: 200,
                child: Image(
                  image: NetworkImage(networkImage),
                ),
              ),
            ]
          ],
        ),

Enter fullscreen mode Exit fullscreen mode

Image description

Using a method

 body: Center(
        child: getWidget(),
      ),
Enter fullscreen mode Exit fullscreen mode
  getWidget() {
    return networkImage == null
        ? Container(
            height: 200,
            width: 200,
            child: Image(
              image: AssetImage('assets/asset_img.jpeg'),
            ),
          )
        : Container(
            height: 200,
            width: 200,
            child: Image(
              image: NetworkImage(networkImage),
            ),
          );
  }
Enter fullscreen mode Exit fullscreen mode

Image description

Using the switch statement

First of all make method switchWithMonth()

void switchWithMonth() {
    switch (month) {
      case 'January':
        print('Running Month is January');
        break;

      case 'February':
        print('Running Month is February');
        break;

      case 'March':
        print('Running Month is March');
        break;

      case 'April':
        print('Running Month is April');
        break;

      case 'May':
        print('Running Month is May');
        break;

      case 'June':
        print('Running Month is May');
        break;

      case 'July':
        print('Running Month is May');
        break;

      case 'August':
        print('Running Month is May');
        break;

      default:
        print('Running Month is January');
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Using the switch statement - Fluttercorner.com'),
        backgroundColor: Colors.green,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              margin: const EdgeInsets.fromLTRB(20, 0, 20, 0),
              child: RaisedButton(
                onPressed: () => switchWithMonth(),
                child: Text('Use Switch Case'),
                textColor: Colors.white,
                color: Colors.green,
                padding: EdgeInsets.fromLTRB(12, 12, 12, 12),
              ),
            ),
          ],
        ),
      ),
    );
  }
Enter fullscreen mode Exit fullscreen mode

Image description

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

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

Using Multiple Conditions:

bool loading = false;
bool error = true;
Enter fullscreen mode Exit fullscreen mode
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
)
Enter fullscreen mode Exit fullscreen mode
int y = 5;
Enter fullscreen mode Exit fullscreen mode
Container( 
    child: y >= 10?
           Text("Y is greater than or equal to 10"):
           Text("Y is less than 10")
)
Enter fullscreen mode Exit fullscreen mode

Method 2: Apply IF....ELSE like below on Children property

:

int a = 10;
Enter fullscreen mode Exit fullscreen mode
Column(
  children: [ 
    if(a > 10)...[
      Text("A is greater than 10"),
    ]else...[
      Text("A is less than or Equal to 10")
    ]
])
Enter fullscreen mode Exit fullscreen mode

You can apply this method of conditional statement on widget tree which has "children" property, for example, Column(), Row(), Wrap() widgets.

Method 3: 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");
        }  
    })
)
Enter fullscreen mode Exit fullscreen mode

Method 4: 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");
     }
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)