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

Flet中IconButton的ButtonStyle animation_duration属性不生效问题

Flet IconButton 颜色切换动画失效问题

问题现象

使用Flet开发时,给IconButton的ButtonStyle配置了默认/悬浮状态的color,同时设置animation_duration=500,但鼠标悬浮切换图标颜色时完全没有平滑过渡动画。换成TextButton用相同配置,文字颜色的平滑切换动画却能正常生效。

问题代码(IconButton无动画)

import flet


def main(page: flet.Page):
    page.add(
        flet.IconButton(
            icon="delete",
            style=flet.ButtonStyle(
                color={
                    flet.MaterialState.HOVERED: flet.colors.WHITE,
                    flet.MaterialState.DEFAULT: flet.colors.BLACK,
                },
                animation_duration=500,
            ),
        )
    )


flet.app(target=main)

预期效果代码(TextButton正常动画)

import flet


def main(page: flet.Page):
    page.add(
        flet.TextButton(
            "delete",
            style=flet.ButtonStyle(
                color={
                    flet.MaterialState.HOVERED: flet.colors.WHITE,
                    flet.MaterialState.DEFAULT: flet.colors.BLACK,
                },
                animation_duration=500,
            ),
        )
    )


flet.app(target=main)

原因与解决办法

Flet的IconButton内部未将图标颜色切换逻辑与ButtonStyle的animation_duration绑定,而TextButton的文字颜色动画则直接复用了该配置。要实现IconButton的颜色切换动画,需手动添加动画逻辑:

方案一:通过on_hover事件实现

import flet


def main(page: flet.Page):
    def on_hover(e):
        # 根据悬浮状态切换图标颜色,组件更新时触发动画
        e.control.icon_color = flet.colors.WHITE if e.data == "true" else flet.colors.BLACK
        e.control.update()

    btn = flet.IconButton(
        icon="delete",
        icon_color=flet.colors.BLACK,
        style=flet.ButtonStyle(animation_duration=500)
    )
    btn.on_hover = on_hover
    page.add(btn)


flet.app(target=main)

方案二:用AnimatedContainer包裹图标(更灵活)

import flet


def main(page: flet.Page):
    is_hovered = False

    def toggle_hover(e):
        nonlocal is_hovered
        is_hovered = e.data == "true"
        container.update()

    container = flet.AnimatedContainer(
        duration=500,
        content=flet.Icon(name="delete", color=flet.colors.WHITE if is_hovered else flet.colors.BLACK),
        on_hover=toggle_hover
    )
    page.add(container)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 01:23:22