Search code examples
flutterdartif-statementwidgetcontainers

How to create image with if conditions on flutter?


There is a container with an image inside like this

Container(

              child: GestureDetector(
                onDoubleTap: () {
                  //print("double tap");
                  showAlertDialog(context);
                  call(url);
                },
                //child: Image.asset('resimler/primeLogo.png'),

                child: Image.memory(
                    image!,
                    fit: BoxFit.contain,
                    width: MediaQuery.of(context).size.width * 0.3,
                    height: MediaQuery.of(context).size.height * 0.3),
              ),

This container allows me to display an image within the page. However I want this image to be displayed only when the x variable is greater than 100, otherwise it will not occur at all. To do this, I tried this.

if(x>100){
              return new Container(
                child: GestureDetector(
                onDoubleTap: () {
                  //print("double tap");
                  showAlertDialog(context);
                  call(url);
                },
                //child: Image.asset('resimler/primeLogo.png'),

                child: Image.memory(
                    image!,
                    fit: BoxFit.contain,
                    width: MediaQuery.of(context).size.width * 0.3,
                    height: MediaQuery.of(context).size.height * 0.3),
              ),

            )],
          }else{
              return null;
    }

How to i do that? Thanks for your help.


Solution

  • You can use this (x>0) ? Widget() : Widget() condition.

    Container(
    
              child: GestureDetector(
                onDoubleTap: () {
                  //print("double tap");
                  showAlertDialog(context);
                  call(url);
                },
                //child: Image.asset('resimler/primeLogo.png'),
    
                child: (x > 100) ? Image.memory(
                    image!,
                    fit: BoxFit.contain,
                    width: MediaQuery.of(context).size.width * 0.3,
                    height: MediaQuery.of(context).size.height * 0.3),
              ) : Container(),
           ),
        ),