首页 > 解决方案 > 在 Flutter 中切换容器

问题描述

如何在附图中实现自定义切换类型的背景。我想更改背景颜色和图标更改 onTap。在此处输入图像描述

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

                                        setState(() {

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

标签: flutterbuttontogglegesture

解决方案


您可以轻松地为颜色和图标设置一个变量,以便当您发生 onTap 时,它会更改该变量,然后更改 setState。下面我包含了一小段代码,以进一步说明我要解释的内容。如果您在使用您已经编写的代码实现我的概念时遇到任何问题,请告诉我并向我展示您的一些代码,我可以提供帮助!

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

推荐阅读