Ad

Switch Case Inside A Container

- 1 answer

I have a rectangle and I'm trying to change it's colour based on the boolean true or false. But switch statement seems like it's not in the correct place and it says expected an identifier. Where to place Switch logic?

Stack(
        alignment: Alignment.center,
        children: <Widget>[
          SizedBox(
            width: circleSize,
            height: circleSize,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: Container(
               
               switch (OnOffVariable) {
                  case false:
                     color: Colors.grey,
                    break;
                  default: color: Colors.purple,

                  case true:
                     color: Colors.purple,
                    break;
                  default: color: Colors.purple,

                },
              )
              ),
            ),
Ad

Answer

You don't need to use switch-case if it only has two condition. Use ternary operator will do.

child: Container(color: OnOffVariable == false ?
                      Colors.grey : Colors.purple)
Ad
source: stackoverflow.com
Ad