flutteruser-interfacebuttontogglegesture

Toggle container colors on selected


I want to know how to implement the logic of toggling the background and foreground colors of a Container when selected as in the following image:

desired_ui

I have tried the following:

return GestureDetector(
  onTap: () {
    if (white == Colors.blue)
      white = Colors.white;
    else
      white = Colors.white;

    setState(() {});
  },
  child: Container(
    width: 100,
    height: 100,
    color: white,
  ),
);

Solution

  • Something you can easily do would to set a variable for both the color and icon so that when you have the onTap occur it would change that variable and then setState. Below I have included a short bit of code to further show what I am trying to explain. If you have any issues implementing my concept with the code you already have written just let me know and show me some of your code and I can help!

    Widget theCard() {
        Color theColor;
        IconData theIcon;
    
        return GestureDetector (
            onTap: () {
                if(theColor == Colors.blue) {
                    theColor = Color.white;
                    theIcon = Icons.check;
                }
                else {
                    theColor = Colors.blue;
                    theIcon = Icons.remove;
                }
                setState(() {
                
                })
            },
            child: Container(
                color: theColor, 
                child: Icon(theIcon)
            )
        )
    }