You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中GestureDetector点击后Container未变色问题求助

问题解决建议

你的代码里有两个关键错误导致点击后状态没变化:

  • 函数未实际调用:GestureDetector的onTap回调中,你只写了buttonPressed,这只是引用函数对象,没有执行它,必须加上括号buttonPressed()才会触发函数执行。
  • 赋值运算符误用:buttonPressed函数里用了比较运算符==来尝试修改savePressed的值,这不会改变变量状态,正确的赋值应该用单等号=。

另外,切换布尔值可以简化写法,不用if-else判断,直接savePressed = !savePressed即可,代码更简洁。

修正后的完整代码:

import 'package:flutter/material.dart';

class VotingButton extends StatefulWidget {
  @override
  State<VotingButton> createState() => _VotingButtonState();
}

class _VotingButtonState extends State<VotingButton> {
  bool savePressed = false;

  void buttonPressed() {
    setState(() {
      // 简化布尔值切换写法
      savePressed = !savePressed;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 18.0),
      child: GestureDetector(
        onTap: () {
          buttonPressed(); // 修正:调用函数
          print(savePressed);
        },
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(6),
            color: savePressed ? Colors.blue : Colors.red[400],
          ),
          child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 40),
            child: Text(
              'I\'ll be Here!',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
          ),
        ),
      ),
    );
  }
}

内容的提问来源于stack exchange,提问作者BrainStormer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 05:36:00