Skip to main content

Getting user input

Making interactive web apps with Flet is a breeze! It's not just limited to displaying data, but you can request an input from a user and respond to various events generated by page controls.

Buttons

Button is the most essential input control which generates click event when pressed:

btn = ElevatedButton("Click me!")
page.add(btn)

[SCREENSHOT?]

All events generated by controls on a web page are continuously sent back to your script, so how do you respond to a button click?

Event handlers

Buttons with events in "Counter" app:

import flet
from flet import IconButton, Page, Row, TextField, icons

def main(page: Page):
page.title = "Flet counter example"
page.vertical_alignment = "center"

txt_number = TextField(value="0", text_align="right", width=100)

def minus_click(e):
txt_number.value = int(txt_number.value) - 1
page.update()

def plus_click(e):
txt_number.value = int(txt_number.value) + 1
page.update()

page.add(
Row(
[
IconButton(icons.REMOVE, on_click=minus_click),
txt_number,
IconButton(icons.ADD, on_click=plus_click),
],
alignment="center",
)
)

flet.app(target=main)

Textbox

Flet provides a number of controls for building forms: TextField, Checkbox, Dropdown, ElevatedButton.

Let's ask a user for a name:

greeter.py
import flet
from flet import ElevatedButton, Text, TextField

def main(page):
def btn_click(e):
if not txt_name.value:
txt_name.error_text = "Please enter your name"
page.update()
else:
name = txt_name.value
page.clean()
page.add(Text(f"Hello, {name}!"))

txt_name = TextField(label="Your name")

page.add(txt_name, ElevatedButton("Say hello!", on_click=btn_click))

flet.app(target=main)

Checkbox

TBD

TBD