Flet · lesson 4 of 6
Parts in this lesson
A@ft.controlmakes the class a dataclass
Bclass ItemCard(ft.Container)4.5: a subclass
Ctitle: str = ""3.6: a typed field
Ddef init(self)set up after the fields

Your own controls

Last updated

Flet's own controls are dataclasses, so yours are too. In this lesson you'll make a control of your own by subclassing one of Flet's, give it typed fields, set it up in init instead of __init__, and keep its state inside it. Then you'll read the reference's whole desk, which is one custom control.

By the end of this lesson you can

  • Make a custom control with @ft.control and a subclass of a Flet control
  • Give a control fields with types, and explain the error a mutable default gives
  • Set a control up in init, and say why it doesn't write __init__
  • Keep an app's state in a control's attributes, with handlers as its methods

Fields with types

A Flet control is a dataclass, so a control of your own is one too, and its fields are listed the dataclass way: a name, a type and usually a default (lesson 3.6). Here's a pretend card for one library item, as a plain dataclass. Press Run:

Step 1 code fields.py
Edit the code, then run it again
  • Every field has a type. Without one, @dataclass doesn't see a field at all, just a class attribute (lesson C.2's ClassVar was the same idea, on purpose).
  • __post_init__ runs once the fields are set. Flet's version of it is called init, in step 3.
  • tags gets field(default_factory=list), so each card gets its own new list. Appending to Dune's tags leaves Emma's empty.

A list as a default

The wrong way. Why not just tags: list[str] = []? Press Run:

Step 2 code shared.py
Edit the code, then run it again

Read the last line: a mutable default isn't allowed, so use default_factory. It stops before any card is made, on the class itself.

Here's what it saves you from. A default is made once, when the class is made, and shared. If every card shared one list, adding a tag to Dune would add it to every card. It's the trap lesson 2.5 showed with def add_loan(title, loans=[]). Dataclasses refuse it outright for list, dict and set.

field(default_factory=list), from lesson 3.6, hands @dataclass a function to call instead: list() makes a new empty list for each object. Flet's own controls do the same for their controls lists, and so must yours.

An item card

Now a real Flet control. Save this as card.py and run it:

import flet as ft


@ft.control
class ItemCard(ft.Container):
    """One library item, as a card with a button. Its fields need types."""

    title: str = ""
    state: str = "In"

    def init(self) -> None:
        self.padding = 12
        self.label = ft.Text(f"{self.title}: {self.state}")
        self.content = ft.Row(
            controls=[self.label, ft.Button(content="Lend", on_click=self.lend)]
        )

    def lend(self, e: ft.Event[ft.Button]) -> None:
        self.state = "Out"
        self.label.value = f"{self.title}: {self.state}"


def main(page: ft.Page) -> None:
    page.title = "Library desk"
    page.add(ItemCard(title="Dune"), ItemCard(title="Emma"))


ft.run(main)
Two rows, Dune: In and Emma: In, each with a Lend button
card.py: two cards, before any clicks.

Two cards appear, each with a Lend button. Press Dune's, and only Dune's says Out.

  • @ft.control turns the class into a dataclass, the way Flet's own controls are made, and registers it with Flet.
  • ItemCard is a Container (lesson 4.5), so it has a container's fields too, like padding and content.
  • title and state are the card's own fields. ItemCard(title="Dune") sets them by name.
  • init runs once the fields are set, like __post_init__. It builds what's inside the card. The label is kept as self.label so lend can change it.
  • lend is a method, and each card's button calls its own card's lend. Each card keeps its own state. That's encapsulation (lesson 4.2): the page never reaches inside a card.

Why not write __init__? Because @ft.control writes it, from the fields, as @dataclass does. Old tutorials write their own __init__ and call super().__init__(); in Flet 1, use fields and init instead.

Flet has other methods it calls at set times, called lifecycle hooks: did_mount once the control is on the page, will_unmount just before it's taken off, and before_update before each redraw. Override one to do something at that moment, like starting a timer when a control appears.

When does Flet call a custom control's init?

The desk as one control

The reference's whole desk is a single custom control, DeskView, a subclass of Column. Its one field is the presenter it's handed (lesson F.3):

How the reference does it library_gui/flet_app.py, lines 18–79
@ft.control
class DeskView(ft.Column):
    """The whole desk as one control. Flet makes it a dataclass: fields need types."""

    # Flet sends a control's fields to the screen. The presenter stays in Python,
    # so its field is marked "skip".
    presenter: LibraryPresenter | None = field(default=None, metadata={"skip": True})

    def init(self) -> None:
        self.chosen = ""
        self.search = ft.TextField(label="Search", on_change=self.searched)
        self.member = ft.Dropdown(
            label="Member",
            options=[ft.DropdownOption(key=i, text=name) for i, name in self.presenter.members()],
        )
        self.table = ft.DataTable(
            columns=[ft.DataColumn(label=ft.Text(name)) for name in ("Title", "Kind", "State", "Due")]
        )
        self.status = ft.Text("Choose an item, then lend it or take it back.")
        self.controls = [
            self.search,
            self.table,
            ft.Row(
                controls=[
                    self.member,
                    ft.Button(content="Lend", on_click=self.lend),
                    ft.Button(content="Return", on_click=self.give_back),
                ]
            ),
            self.status,
        ]
        self.refresh()

    def make_row(self, row: Row) -> ft.DataRow:
        return ft.DataRow(
            cells=[ft.DataCell(ft.Text(v)) for v in (row.title, row.kind, row.state, row.due)],
            selected=row.item_id == self.chosen,
            on_select_change=lambda e: self.choose(row.item_id),
        )

    def refresh(self) -> None:
        self.table.rows = [self.make_row(row) for row in self.presenter.rows(self.search.value)]

    def choose(self, item_id: str) -> None:
        self.chosen = item_id
        self.refresh()

    def searched(self, e: ft.Event[ft.TextField]) -> None:
        self.refresh()

    def lend(self, e: ft.Event[ft.Button]) -> None:
        self.show(self.presenter.lend(self.chosen, self.member.value or ""))

    def give_back(self, e: ft.Event[ft.Button]) -> None:
        self.show(self.presenter.give_back(self.chosen))

    def show(self, message: Message) -> None:
        self.status.value = message.text
        if not message.ok:
            self.page.show_dialog(ft.SnackBar(ft.Text(message.text)))
        self.refresh()
  • init builds the search box, the member drop-down, the table and the buttons, keeps the ones it needs as attributes, and fills self.controls, the column's list.
  • presenter is a field, so DeskView(presenter=...) sets it. But it's made with field(default=None, metadata={"skip": True}). Flet sends every field of a control to the screen, and a presenter can't be sent: without the mark, Flet stops with TypeError: can not serialize 'LibraryPresenter' object. "skip" tells Flet the field stays in Python.
  • self.chosen is the desk's state: the item picked in the table. It's an ordinary attribute, not a field, because nothing outside sets it.
  • Every handler is a method: searched, lend, give_back. Each one asks the presenter, then calls refresh or show.
  • refresh rebuilds the table's rows from the presenter's rows. Lesson F.5 looks at the table and the pop-up in show.

main only sets up the page and adds DeskView(presenter=...). All the desk's code lives in its class.

Check

A custom control has tags: list[str] = []. What happens?
Why does a Flet 1 custom control use init instead of writing __init__?
Where does DeskView keep the item the user picked?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python