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

Flutter问题:点击InkWell后自定义复选框图片不切换

问题原因及修复方案

你的问题出在变量作用域上:imgName被定义在build方法内部,每次调用setState()触发组件重建时,build方法会重新执行,imgName会被重新初始化为'images/checkbox_off.png',之前在setState里的修改直接被覆盖了,所以图片看起来没变化。

修复方法很简单,把imgName提升为_CustomCheckboxState类的成员变量,让它的状态能在组件重建时被保留:

import 'package:flutter/material.dart';

class CustomCheckbox extends StatefulWidget {
  const CustomCheckbox({super.key});

  @override
  State<CustomCheckbox> createState() => _CustomCheckboxState();
}

class _CustomCheckboxState extends State<CustomCheckbox> {
  // 把变量移到类成员位置,初始化默认值
  var imgName = 'images/checkbox_off.png';

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        print("tapped");
        setState(() {
          if (imgName == 'images/checkbox_off.png') {
            imgName = 'images/checkbox_on.png';
          } else {
            imgName = 'images/checkbox_off.png';
          }
        });
      },
      child: Container(
          width: 20.0,
          height: 20.0,
          decoration: BoxDecoration(
              image: DecorationImage(
                  fit: BoxFit.fill, image: AssetImage(imgName)))),
    );
  }
}

这样每次点击触发setState后,imgName的修改会被保留,组件重建时会使用更新后的变量值,图片就能正常切换了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 10:20:13