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

Flutter Container组件鼠标悬停时修改边框颜色无效问题排查

Flutter Container组件鼠标悬停时修改边框颜色无效问题排查

Hey there! Let's dig into why your hover border color isn't working as expected, and check both the code logic and scope issues.

First, let's break down the problems in your current code:

  • UI isn't being refreshed: Since you're using the ft. prefix (Flet framework), modifying a component's property alone won't update the interface. You need to explicitly tell the framework to refresh the component after changing its attributes.
  • Potential scope issues: If your b Container is defined inside a function (like a main app function), the showb callback might not have proper access to the b variable unless you handle the scope correctly.

Here's the fixed version of your code with explanations:

import flet as ft

def main(page: ft.Page):
    # Make sure 'a' is a valid Flet component (example here uses a Text widget)
    a = ft.Text("Your content here", color=ft.colors.BLACK)
    
    def showb(e):
        # Use 'nonlocal' to access the 'b' variable from the outer function scope
        nonlocal b
        # Update the border style
        b.border = ft.border.all(1, ft.colors.WHITE)
        # Critical line: Tell Flet to refresh the Container component
        b.update()
    
    b = ft.Container(
        content=a,
        border=ft.border.all(1, ft.colors.GREY_700),
        border_radius=20,
        width=446,
        on_hover=showb
    )
    
    page.add(b)

ft.app(target=main)

Key fixes and checks:

  1. Added b.update(): This is the most important fix. Without calling update(), Flet has no idea you changed the border property, so it won't re-render the Container to show the new color.
  2. Handled scope with nonlocal: If you're defining b inside a function (like main), the nested showb function needs the nonlocal keyword to reference the outer b variable. Without this, Python would treat b as a local variable inside showb, leading to errors or no changes.
  3. Verified a is defined: Your original code uses content=a—make sure a is a valid Flet widget (like Text, Column, etc.), otherwise the Container won't display content properly.

Give this adjusted code a try, and your hover border color should work as intended!

备注:内容来源于stack exchange,提问作者Sumit Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 12:22:57