Search code examples
flutterbuttontogglegesture

Toggle container in Flutter


How to achieve the custom toggle type of background in the image attached. I want to change the background color and icon changes onTap.enter image description here

 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)
            )
        )
    }