What Are Controls?

In Flet, user interfaces are built using controls (also known as widgets). To make controls visible, they must be added to a Page or nested inside other controls.

The Page control serves as the root of the control tree, with all other controls being nested within it. Controls in Flet are simply Python classes that you instantiate and modify through their properties.

Adding Controls to a Page

To display a control on a page, you need to add it to the page's control list and call page.update() to send the changes to the browser or desktop client.

Example:

import flet as ft

def main(page: ft.Page):
    t = ft.Text(value="Hello World!", color="green")
    page.controls.append(t)
    page.update()

ft.app(target=main)

Modifying Control Properties

You can modify the properties of a control and update the UI using page.update().

Example:

import flet as ft
import time

def main(page: ft.Page):
    t = ft.Text()
    page.add(t)

    for i in range(10):
        t.value = f"Step {i}"
        page.update()
        time.sleep(1)

ft.app(target=main)

Container Controls

Some controls, like Page, act as container controls that hold other controls. For example, the Row control arranges multiple controls in a horizontal line.

Example:

import flet as ft

def main(page: ft.Page):
    page.add(
        ft.Row(controls=[
            ft.Text("A"),
            ft.Text("B"),
            ft.Text("C")
        ])
    )

ft.app(target=main)

You can also combine multiple controls like TextField and ElevatedButton inside a row.

Example:

import flet as ft

def main(page: ft.Page):
    page.add(
        ft.Row(controls=[
            ft.TextField(label="Seu nome"),
            ft.ElevatedButton(text="Diga meu nome!")
        ])
    )

ft.app(target=main)

Handling Changes in Controls

The page.update() function is optimized to only send the changes made since the last update. This means you can add, remove, and modify controls efficiently before calling page.update().

Example:

import flet as ft
import time

def main(page: ft.Page):
    for i in range(10):
        page.controls.append(ft.Text(f"Line {i}"))
        if i > 4:
            page.controls.pop(0)
        page.update()
        time.sleep(0.3)

ft.app(target=main)

Conclusion

Controls are the fundamental building blocks of a Flet application. By understanding how to create, modify, and organize them, you can design dynamic and responsive user interfaces efficiently. Experiment with different controls to build your custom UI in Flet!