如何在点击时改变图标的颜色,并在释放时恢复到默认颜色。

问题描述 投票:0回答:1

我有一个场景,当一个按钮被按下时,按钮的颜色应该改变,然后当我释放按钮时,颜色应该变回默认颜色。

我使用GestureDetector部件来实现这个功能,有人能帮帮我吗?

bool color = false;

GestureDetector(
   onTap: () {
       setState(() {
          if (age > 3) {
              color = true;
               age--;
          } 
          color = false;
       });
   },
   child: Icon(
       Icons.indeterminate_check_box,
       color: color
         ? kSelectedIconColor
         : kAppbarColor,
       size: 40.0,
   )
)
flutter logic flutter-layout flutter-animation gesturedetector
1个回答
1
投票
class TapIcon extends StatefulWidget {
  @override
  _TapIconState createState() => _TapIconState();
}

class _TapIconState extends State<TapIcon> {
  bool tapped = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: (_) {
        setState(() {
          tapped = true;
        });
      },
      onTapUp: (_) {
        setState(() {
          tapped = false;
        });
      },
      child: Icon(
        Icons.indeterminate_check_box,
        color: tapped
            ? kSelectedIconColor
            : kAppbarColor,
        size: 40.0,
      ),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.