Flet · lesson 5 of 6
Parts in this lesson
Aft.DataTable(columns=..., rows=...)a table
Bpage.show_dialog(ft.SnackBar(...))a message at the bottom
Cft.AlertDialog(actions=[...])a question
Dasync def ... await asyncio.sleep(3)waiting without stopping

Tables, dialogs and slow work

Last updated

The library app needs a table to pick items from, a way to show refusals, and a question before it does anything it can't undo. In this lesson you'll fill a DataTable from the presenter, show messages in a SnackBar, ask in an AlertDialog, and keep the app answering while something slow happens.

By the end of this lesson you can

  • Fill a DataTable from the presenter, and react when a row is picked
  • Show a message in a SnackBar, and ask a question in an AlertDialog
  • Explain why time.sleep in a handler stops the app
  • Wait without stopping the app, with an async handler

The catalogue as a table

A DataTable has columns, each a DataColumn with a heading, and rows, each a DataRow of DataCells. Here's how the reference's desk (lesson F.4) makes a row from one of the presenter's Rows, and fills the table:

How the reference does it library_gui/flet_app.py, lines 51–63
    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()
  • Each DataCell holds a control, here a Text with one of the row's strings.
  • selected= highlights the row that's picked.
  • on_select_change is called when the user taps the row. The lambda takes the event, ignores it, and calls choose with this row's id.
  • refresh replaces the whole rows list with new rows from the presenter. It never adds to the old list, so a search can't double the table: setting a field to a new list is the Flet way to empty and refill.

choose keeps the id in self.chosen and refreshes, so the highlight moves. Flet redraws once the handler returns.

There's one trap in make_row. The lambda uses row, a parameter of make_row, so each row's lambda keeps its own row. If the lambdas were made in a loop straight inside refresh, they'd all see the loop's last row by the time they're called. A separate method for one row avoids it.

Messages and questions

The presenter's refusals need showing. The reference puts every message in a status line, and a refusal in a SnackBar too: a short message that slides up from the bottom of the app and goes by itself:

How the reference does it library_gui/flet_app.py, lines 74–78
    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()
The Flet desk after a refusal: the status line and a dark SnackBar at the bottom both say Sorry: Atlas of the World can’t be borrowed
The reference app after trying to lend the Atlas: the message in the status line, and in a SnackBar along the bottom.

page.show_dialog shows anything that pops up over the page. self.page is the page the control is on, which every control on a page knows.

To ask a question, show an AlertDialog: a title, and buttons, called actions. Save this as dialog.py and run it:

import flet as ft


def main(page: ft.Page) -> None:
    status = ft.Text("Dune is on loan.")

    def take_back(e: ft.Event[ft.Button]) -> None:
        page.pop_dialog()
        status.value = "Dune is back."
        page.show_dialog(ft.SnackBar(ft.Text("Dune is back, on time.")))

    ask = ft.AlertDialog(
        title=ft.Text("Take Dune back?"),
        actions=[
            ft.Button(content="Take it back", on_click=take_back),
            ft.Button(content="Cancel", on_click=lambda e: page.pop_dialog()),
        ],
    )
    page.add(status, ft.Button(content="Return", on_click=lambda e: page.show_dialog(ask)))


ft.run(main)

Press Return. The dialog asks; Take it back closes it with page.pop_dialog(), changes the text and shows a SnackBar. Cancel only closes it. Nothing happens until the user chooses.

When should an app ask in an AlertDialog instead of just doing it?

A slow handler

The wrong way. Some jobs take a while, like saving to a slow network drive. Here's a pretend one, with time.sleep(3). Save it as slow.py, run it, and press Save two or three times quickly:

import time

import flet as ft


def main(page: ft.Page) -> None:
    status = ft.Text("Ready")

    def save_slowly(e: ft.Event[ft.Button]) -> None:
        status.value = "Saving..."
        time.sleep(3)  # pretend saving takes three seconds
        status.value = "Saved."

    page.add(status, ft.Button(content="Save", on_click=save_slowly))


ft.run(main)

The app stops answering for three seconds at a time, and Saving... never shows. The handler holds on to the app while it sleeps: Flet only redraws once it returns, and by then the text says Saved.. Clicks made meanwhile wait their turn.

The fix is an async handler. Save this as wait.py and do the same:

import asyncio

import flet as ft


def main(page: ft.Page) -> None:
    status = ft.Text("Ready")

    async def save_slowly(e: ft.Event[ft.Button]) -> None:
        status.value = "Saving..."
        status.update()
        await asyncio.sleep(3)  # waits without stopping the app
        status.value = "Saved."

    page.add(status, ft.Button(content="Save", on_click=save_slowly))


ft.run(main)
  • async def makes the handler a coroutine: a function that can pause part-way and let other things run.
  • await asyncio.sleep(3) pauses this handler for three seconds. Unlike time.sleep, it gives the app back while it waits, so other clicks are handled.
  • status.update() sends Saving... to the screen straight away, before the wait (lesson F.2). Without it, the screen would only change when the handler finishes.

Flet calls an async handler the same way as any other: just pass it to on_click. asyncio is in the standard library, and await only works inside an async def. For real slow work, await something that's made to wait, like asyncio.sleep or a network library's async methods; a slow ordinary function call would still hold the app.

Check

How does the reference empty and refill its DataTable?
Why does time.sleep(3) in a handler stop the app?
What does await asyncio.sleep(3) do in an async handler?

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