如何解决Flet中“Control must be added to the page first”错误?
问题根源
你的代码存在两个核心问题:
- 未将
NavigationDrawer实例绑定到页面的drawer属性(你注释掉了self.page.drawer = self.drawer),导致控件从未被添加到页面中。 - 调用
self.drawer.update()尝试更新未挂载的控件,正确的做法是更新整个页面——因为抽屉是页面的一部分。
修改步骤
- 在
NavigationPanel的__init__方法中取消注释self.page.drawer = self.drawer,将抽屉绑定到页面。 - 修改
show_drawer方法,将self.drawer.update()替换为self.page.update(),通过更新页面触发抽屉显示。
修改后的完整代码
from flet import * from sidebar.sidebar import ModernNavBar class NavigationPanel(UserControl): def __init__(self, page): super().__init__() self.page = page self.drawer = NavigationDrawer( indicator_shape=None, controls=[ Container( height=200, bgcolor='BLUE900', content=Text("Welcome!", weight='BOLD', size=20), margin=10, padding=10, border_radius=10, alignment=alignment.center, on_click=lambda e: print("Clickable without Ink clicked!"), ), ModernNavBar(), ] ) # 取消注释,将抽屉绑定到页面 self.page.drawer = self.drawer def show_drawer(self, e): self.drawer.open = True # 更新页面而非单独更新抽屉 self.page.update() print('Beans') def ApBr(self): return AppBar( title=Text('Main', weight='bold', size=18, color='WHITE'), leading=IconButton(icons.MENU, on_click=self.show_drawer), bgcolor='BLUE800' ) def build(self): return self.ApBr() def main(page: Page): page.title = 'Hello' page.horizontal_alignment = 'center' page.vertical_alignment = 'center' page.window_width = 400 page.window_height = 800 page.theme_mode = ThemeMode.DARK menu = NavigationPanel(page) def route_change(e: RouteChangeEvent) -> None: page.views.clear() page.views.append( View( route='/', controls=[ Text(value='MENU', size=50, color='white', font_family='bl'), IconButton( icon=icons.NAVIGATE_NEXT, icon_color="blue400", icon_size=40, tooltip="Open", on_click=lambda _: page.go('/main'))], vertical_alignment=MainAxisAlignment.CENTER, horizontal_alignment=CrossAxisAlignment.CENTER, spacing=26, ), ) # Account View if page.route == "/main": page.views.append( View( route='/main', controls=[ menu.ApBr(), FloatingActionButton( icon=icons.ARROW_BACK_IOS_ROUNDED, bgcolor='BLUE900', on_click=lambda _: page.go('/') ), Text( value='Hello', size=25, text_align=TextAlign.CENTER ), ElevatedButton( "Drawer", on_click=menu.show_drawer), ], vertical_alignment=MainAxisAlignment.CENTER, horizontal_alignment=CrossAxisAlignment.CENTER, ) ) page.update() def view_pop(e: ViewPopEvent) -> None: page.views.pop() top_view: View = page.views[-1] page.go(top_view.route) page.on_route_change = route_change page.on_view_pop = view_pop page.go(page.route) app(target=main)
额外说明
- Flet的
NavigationDrawer是页面的顶级控件,必须通过page.drawer赋值才能被页面识别。 - 对页面顶级控件的修改,需要调用
page.update()刷新界面,而非单独更新控件本身。
内容的提问来源于stack exchange,提问作者Teddy
相关产品推荐
相关产品推荐

