Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to use if condition in the icon widget, but Dart gives an error. How should it be used correctly? Thanks.

class Cell extends StatelessWidget {
  const Cell({super.key, this.caseTrend = false});

  final bool caseTrend;

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          const Text("23.410"),
          Icon(
          if(caseTrend) { //<== getting error here: Expected an identifier.dart Expected to find ')'.
            Icons.trending_up,
            color: Colors.green,
          } 
          else
          {
            Icons.trending_down,
            color: Colors.red,
          },
            size: 24, 
          )
        ],
      ),
    );
  }
}


What I have tried:

class Cell extends StatelessWidget {
  const Cell({super.key, this.caseTrend = false});

  final bool caseTrend;

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          const Text("23.410"),
          Icon( //This way working well but using conditions two times
           caseTrend ? Icons.trending_up : Icons.trending_down, 
           color: caseTrend ? Colors.green : Colors.red,
            size: 24, 
          )
        ],
      ),
    );
  }
}
Posted
Updated 28-Jan-24 10:28am
v2

1 solution

Unfortunately, you can’t write if statement directly inside your widget properties as if you were writing in your method or function. But there are a few ways you can write a conditional statement inside your widget. You can use the ternary operator (condition ? expr1 : expr2) to achieve conditional rendering within the widget property, as you mentioned what you have tried. Here is the reference link to use some other alternative solutions to use inside widget properties.
Flutter if else: Top 3 ways you need to know (Code) [January 2024] - FlutterBeads[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900