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

Flutter开发中IconButton触发onPressed后Icon图标不更新问题求助

问题原因

你代码的状态修改逻辑中误用了相等判断运算符,没有真正修改存储图标的变量值:
你自定义的onPressed方法里的两行逻辑使用的是==(相等判断运算符),执行后仅会返回布尔判断结果,不会对play变量做赋值操作,因此状态从未发生实际变更,图标自然不会切换。

修复方案

把onPressed方法中的==替换为赋值运算符=即可,修改后的对应代码如下:

onPressed(){
  if(play == Icons.play_circle_filled){
    // 把双等号改为单等号完成赋值操作
    play = Icons.pause_circle_filled_rounded;
  } else {
    play = Icons.play_circle_filled;
  }
}
完整可运行修复后代码
import 'package:flutter/material.dart';

void main() {
  runApp(const AllTests());
}

class AllTests extends StatefulWidget {
  const AllTests({Key? key}) : super(key: key);

  @override
  _AllTestsState createState() => _AllTestsState();
}

class _AllTestsState extends State<AllTests> {

  IconData play = Icons.play_circle_filled;
  onPressed(){
    if(play == Icons.play_circle_filled){
      play = Icons.pause_circle_filled_rounded;
    } else {
      play = Icons.play_circle_filled;
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children:  [
              IconButton(
                icon: Icon(
                  play,
                  size: 80,
                  color: Colors.black,
                ), 
                onPressed: () {
                  setState(() {
                    print('hello');
                    onPressed();
                  });
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

内容的提问来源于stack exchange,提问作者Samuella M. Aglago

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 17:36:03