Home > front end >  How to use if else in flutter for icons?
How to use if else in flutter for icons?

Time:08-11

I want to change icons based on information fetched from the database. How can I do that?

if(documentSnapshot['visiting period']=="Sold"){
                            Icon(MyIcons.aquas),

                          },
else{
...
}

Can anyone help with this as I get the error

The element type 'List<Icon>' can't be assigned to the list type 'Widget'.

CodePudding user response:

Try this

Icon(documentSnapshot['visiting period']=="Sold"? Icons.one : Icons.two)),

CodePudding user response:

You can create a method that returns an icon.

body: Container(
    _getApplicableIcon(documentSnapshot['visiting period']);
  ),

_getApplicableIcon(String visitingPeriod) {
    switch (visitingPeriod) {
    case "Sold":
       return Icon(MyIcons.aquas);
    case "Not Sold":
       return Icon(MyIcons.elseIcon);
    default:
       return Icon(MyIcons.defaultIcon);
    }
}

If you dont want an icon as default you can return container();

CodePudding user response:

You can use ternary operator inside the icon widget like this

Icon(true ? Icons.abc : Icons.abc_rounded)

replace true with your condition. the value after ? will be called if the condition is true and the value after : will be called when condition is false

CodePudding user response:

You can achieve that using two way.

documentSnapshot['visiting period']=="Sold" ?  Icon(MyIcons.aquas) : Icon(MyIcons.(your icon name);

Or

Icon(documentSnapshot['visiting period']=="Sold" ? MyIcons.aquas : Icon(MyIcons.(your icon name));
  • Related