[Question] Navigating causes Controls error #1660
-
QuestionHello, I have copied the routing the demo on Navigation and routing (Link) and made some changes adding a button that should append a text element on click It works until the route is navigated (either with the buttons or or the back button in the app bar) then I get the following: AssertionError: Control must be added to the page first. What am I doing wrong? Code sampleimport flet as ft
class Store(ft.UserControl):
def stuff(self, e):
print("Hello")
self.controls.append(ft.Text("Hello"))
self.update()
def build(self):
return ft.ElevatedButton("Store Button", on_click=self.stuff)
def main(page: ft.Page):
page.title = "Routes Example"
store = Store()
def route_change(route):
page.views.clear()
page.views.append(
ft.View(
"/",
[
ft.AppBar(
title=ft.Text("Flet app"), bgcolor=ft.colors.SURFACE_VARIANT
),
ft.ElevatedButton(
"Visit Store", on_click=lambda _: page.go("/store")
),
store,
],
)
)
if page.route == "/store":
page.views.append(
ft.View(
"/store",
[
ft.AppBar(
title=ft.Text("Store"), bgcolor=ft.colors.SURFACE_VARIANT
),
ft.ElevatedButton("Go Home", on_click=lambda _: page.go("/")),
store,
],
)
)
page.update()
def view_pop(view):
page.views.pop()
top_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)
ft.app(target=main) Error messageAssertionError: Control must be added to the page first. ------------------------------------------------------
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
Fixed code: import flet as ft
class Store(ft.UserControl):
def stuff(self, e):
print("Hello")
self.controls.append(ft.Text("Hello"))
self.update()
def build(self):
return ft.ElevatedButton("Store Button", on_click=self.stuff)
def main(page: ft.Page):
page.title = "Routes Example"
def route_change(route):
page.views.clear()
page.views.append(
ft.View(
"/",
[
ft.AppBar(
title=ft.Text("Flet app"), bgcolor=ft.colors.SURFACE_VARIANT
),
ft.ElevatedButton(
"Visit Store", on_click=lambda _: page.go("/store")
),
Store(),
],
)
)
if page.route == "/store":
page.views.append(
ft.View(
"/store",
[
ft.AppBar(
title=ft.Text("Store"), bgcolor=ft.colors.SURFACE_VARIANT
),
ft.ElevatedButton("Go Home", on_click=lambda _: page.go("/")),
Store(),
],
)
)
page.update()
def view_pop(view):
page.views.pop()
top_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)
ft.app(target=main) |
Beta Was this translation helpful? Give feedback.
-
Hello, So you have not initated the classes outside of the routes? Not reusing the same instance of the class? Do they reinit/rebuild when the route changes? I had a print statement in at one point on the build funtion and it was building evenytime the route changed Just trying to understand thisfor the future Thank you! |
Beta Was this translation helpful? Give feedback.
Fixed code: