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

Flutter ExpandIcon组件状态无法切换问题求助

解决Flutter ExpandIcon按钮状态无法切换的问题

问题出在你ExpandIcon的onPressed回调参数命名上——你用了和全局状态变量一样的_isExpanded,导致局部变量覆盖了全局变量,你在setState里修改的只是局部参数,根本没触动全局的状态,所以按钮状态和下方的文本都不会更新。

修复方法很简单,把回调里的参数名改成不一样的,或者直接忽略参数:

修复后的代码示例

bool _isExpanded = true;
Container(
  color: const Color(0xffeaeaea),
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    children: [
      Container(
        child: Text('Description'),
      ),
      ExpandIcon(
        expandedColor: Colors.black,
        color: Colors.black,
        isExpanded: _isExpanded,
        // 方法1:修改参数名,避免和全局变量重名
        onPressed: (bool isExpanded) {
          setState(() {
            _isExpanded = !_isExpanded;
          });
        },
        // 方法2:忽略参数,直接取反全局状态
        // onPressed: (_) {
        //   setState(() {
        //     _isExpanded = !_isExpanded;
        //   });
        // },
      ),
    ],
  ),
),
if (_isExpanded) const Text('Data'),

这样修改后,点击ExpandIcon时就会正确切换全局的_isExpanded状态,按钮图标和下方的文本都会正常更新了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 17:12:02