Repository navigation
[Question] About app architecture #6884
Question作为一个ui工具包或许不应该对于应用架构指手画脚,尤其在python这个简单自由的语言环境中,但是我作为其他语言的开发者,没有看到标准的MVVM架构的支持示例,我搜索关联到的有相关工具包,比如fletx,我想了解官方是否有推荐的应用架构么? Code sampleNo response Error messageNo response ------------------------------------------------------
|
Replies: 1 comment
|
There's no official MVVM framework in Flet (fletx is a third-party project), but since Flet 1.0 added declarative UI, MVVM maps onto the built-in pieces quite naturally, with no extra library:
When you assign to an observable's fields (or mutate its lists), Flet re-renders the components that read them, so there's no manual from dataclasses import dataclass, field
import flet as ft
# ViewModel: observable state + commands
@ft.observable
@dataclass
class TodoViewModel:
items: list[str] = field(default_factory=list)
draft: str = ""
def set_draft(self, value: str):
self.draft = value
def add(self):
if self.draft.strip():
self.items.append(self.draft.strip())
self.draft = ""
# View: a pure function of the ViewModel
@ft.component
def TodoView(vm: TodoViewModel):
return ft.Column([
ft.Row([
ft.TextField(value=vm.draft, on_change=lambda e: vm.set_draft(e.control.value)),
ft.Button("Add", on_click=vm.add),
]),
*[ft.Text(item) for item in vm.items],
])
@ft.component
def App():
vm, _ = ft.use_state(TodoViewModel())
return TodoView(vm)
ft.run(lambda page: page.render(App))A few practical guidelines:
The official cookbook has a good side-by-side example of this structure: Declarative vs Imperative CRUD app. There's also the announcement post that explains observables and hooks. If you're on an older (pre-1.0) imperative Flet, the equivalent is to subclass a control like |
There's no official MVVM framework in Flet (fletx is a third-party project), but since Flet 1.0 added declarative UI, MVVM maps onto the built-in pieces quite naturally, with no extra library:
@ft.observabledataclass holding UI state + methods as "commands"@ft.componentfunctions that read ViewModel fields and bind events to its methodsWhen you assign to an observable's fields (or mutate its lists), Flet re-renders the components that read them, so there's no manual
page.update()and no binding boilerplate. That's essentially the ViewModel → View data binding you're …