Page
Page is a container for View controls.
A page instance and the root view are automatically created when a new user session started.
Inherits: BasePage
Properties
auth- The current authorization context, orNoneif the user is not authorized.browser_context_menu- DEPRECATED: The BrowserContextMenu service for the current page.client_ip- IP address of the connected user.client_user_agent- Browser details of the connected user.clipboard- DEPRECATED: The Clipboard service for the current page.debug-Trueif Flutter client of Flet app is running in debug mode.executor- The executor for the current page.fonts- Defines the custom fonts to be used in the application.loop- The event loop for the current page.multi_view-Trueif the application is running with multi-view support.multi_views- The list of multi-views associated with this page.name- The name of the current page.platform- The operating system the application is running on.platform_brightness- The current brightness mode of the host platform.pubsub- The PubSub client for the current page.pwa-Trueif the application is running as Progressive Web App (PWA).pyodide-Trueif the application is running in Pyodide (WebAssembly) mode.query- The query parameters of the current page.route- Gets current app route.session- The session that this page belongs to.shared_preferences- DEPRECATED: The SharedPreferences service for the current page.storage_paths- DEPRECATED: The StoragePaths service for the current page.test-Trueif the application is running with test mode.url- The URL of the current page.url_launcher- DEPRECATED: The UrlLauncher service for the current page.wasm-Trueif the application is running in WebAssembly (WASM) mode.web-Trueif the application is running in the web browser.window- Provides properties/methods/events to monitor and control the app's native OS window.
Events
on_app_lifecycle_state_change- Called when app lifecycle state changes.on_close- Called when a session has expired after configured amount of time (60 minutes by default).on_connect- Called when a web user (re-)connects to a page session.on_disconnect- Called when a web user disconnects from a page session, i.e.on_error- Called when unhandled exception occurs.on_keyboard_event- Called when a keyboard key is pressed.on_locale_change- Called when the locale preferences/settings of the host platform have changed.on_login- Called upon successful or failed OAuth authorization flow.on_logout- Called afterpage.logout()call.on_multi_view_add- TBDon_multi_view_remove- TBDon_platform_brightness_change- Called when brightness of app host platform has changed.on_route_change- Called when page route changes either programmatically, by editing application URL or using browser Back/Forward buttons.on_view_pop- Called when the user clicks automatic "Back" button in AppBar control.on_views_pop_until- Called when pop_views_until reaches the destination view.
Methods
before_eventcan_launch_url- Checks whether the specified URL can be handled by some app installed on the device.close_in_app_web_view- Closes in-app web view opened withlaunch_url().error- Report an application error to the current session/client.get_control- Get a control by itsid.get_device_info- Returns device information.get_upload_url- Generates presigned upload URL for built-in upload storage:go- A helper method that updatespage.route, callspage.on_route_changeevent handler to update views and finally callspage.update().launch_url- Opens a web browser or popup window to a givenurl.login- Starts OAuth flow.logout- Clears current authentication context.navigate- Navigate to a new route (sync convenience wrapper).pop_views_until- Pops views from the navigation stack until a view with the givenrouteis found, then deliversresultvia the on_views_pop_until event.push_route- Pushes a new navigation route to the browser history stack.render- Render a component tree into controls of the root view.render_views- Render a component tree as the full list of page views.run_task- Runhandlercoroutine as a new Task in the event loop associated with the current page.run_thread- Runhandlerfunction as a new Thread in the executor associated with the current page.schedule_update- Queue this page for a deferred batched update.set_allowed_device_orientations- Constrains the allowed orientations for the app when running on a mobile device.update- Push pending state changes to the client.
Examples
Listening to keyboard events
import flet as ft
class ButtonControl(ft.Container):
def __init__(self, text):
super().__init__()
self.content: ft.Text = ft.Text(text)
self.border = ft.Border.all(1, ft.Colors.BLACK_54)
self.border_radius = 3
self.bgcolor = "0x09000000"
self.padding = 10
self.visible = False
def main(page: ft.Page):
page.spacing = 50
page.vertical_alignment = ft.MainAxisAlignment.CENTER
page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
def on_keyboard(e: ft.KeyboardEvent):
key.content.value = e.key
key.visible = True
shift.visible = e.shift
ctrl.visible = e.ctrl
alt.visible = e.alt
meta.visible = e.meta
page.update()
page.on_keyboard_event = on_keyboard
page.add(
ft.SafeArea(
content=ft.Column(
controls=[
ft.Text(
"Press any key with a combination of CTRL, ALT, SHIFT "
"and META keys..."
),
ft.Row(
controls=[
key := ButtonControl(""),
shift := ButtonControl("Shift"),
ctrl := ButtonControl("Control"),
alt := ButtonControl("Alt"),
meta := ButtonControl("Meta"),
],
alignment=ft.MainAxisAlignment.CENTER,
),
]
)
)
)
if __name__ == "__main__":
ft.run(main)
Mobile device orientation configuration
Shows how to lock your app to specific device orientations (e.g., portrait up, landscape right) and listen for orientation changes on mobile devices.
import flet as ft
def main(page: ft.Page) -> None:
page.title = "Device orientation lock"
page.appbar = ft.AppBar(
title=ft.Text("Device orientation Playground"),
center_title=True,
bgcolor=ft.Colors.BLUE,
)
def handle_media_change(e: ft.PageMediaData) -> None:
page.show_dialog(
ft.SnackBar(
f"I see you rotated the device to {e.orientation.name} orientation. 👀",
action="Haha!",
duration=ft.Duration(seconds=3),
)
)
page.on_media_change = handle_media_change
async def on_checkbox_change(e: ft.Event[ft.Checkbox]) -> None:
# get selection
selected = [o for o, checkbox in checkboxes.items() if checkbox.value]
# apply selection
await page.set_allowed_device_orientations(selected)
checkboxes: dict[ft.DeviceOrientation, ft.Checkbox] = {
orientation: ft.Checkbox(
label=orientation.name,
value=True,
on_change=on_checkbox_change,
disabled=not page.platform.is_mobile(), # disabled on non-mobile platforms
)
for orientation in list(ft.DeviceOrientation)
}
page.add(
ft.SafeArea(
content=ft.Column(
controls=[
ft.Text(
spans=[
# shown only on mobile platforms
ft.TextSpan(
"Select the orientations that should remain enabled "
"for the app. "
"If no orientation is selected, "
"the system defaults will be used.",
visible=page.platform.is_mobile(),
),
# shown only on non-mobile platforms
ft.TextSpan(
"Please open this example on a mobile device instead.",
visible=not page.platform.is_mobile(),
style=ft.TextStyle(weight=ft.FontWeight.BOLD),
),
],
),
ft.Column(controls=list(checkboxes.values())),
]
)
)
)
if __name__ == "__main__":
ft.run(main)
App exit confirmation
import flet as ft
def main(page: ft.Page):
def window_event(e: ft.WindowEvent):
if e.type == ft.WindowEventType.CLOSE:
page.show_dialog(confirm_dialog)
page.update()
page.window.prevent_close = True
page.window.on_event = window_event
async def handle_yes_click(e: ft.Event[ft.Button]):
await page.window.destroy()
def handle_no_click(e: ft.Event[ft.OutlinedButton]):
page.pop_dialog()
page.update()
confirm_dialog = ft.AlertDialog(
modal=True,
title=ft.Text("Please confirm"),
content=ft.Text("Do you really want to exit this app?"),
actions=[
ft.Button(content="Yes", on_click=handle_yes_click),
ft.OutlinedButton(content="No", on_click=handle_no_click),
],
actions_alignment=ft.MainAxisAlignment.END,
)
page.add(
ft.SafeArea(
content=ft.Column(
controls=[
ft.Text(
'Try exiting this app by clicking window\'s "Close" button!'
)
]
)
)
)
if __name__ == "__main__":
ft.run(main)
Hidden app window on startup
A Flet desktop app (Windows, macOS, or Linux) can start with its window hidden. This lets your app perform initial setup (for example, add content, resize or position the window) before showing it to the user.
In the example below, the window is resized and centered before becoming visible:
import asyncio
import flet as ft
async def main(page: ft.Page):
print("Window is hidden on start. Will show after 3 seconds...")
page.add(
ft.SafeArea(
content=ft.Column(
controls=[
ft.Text("Hello!"),
]
)
)
)
# some configuration that we want to do before showing the window
page.window.width = 300
page.window.height = 200
page.update()
await page.window.center()
# wait for 3 seconds before showing the window
await asyncio.sleep(3)
# show the window
page.window.visible = True
page.update()
if __name__ == "__main__":
ft.run(main, view=ft.AppView.FLET_APP_HIDDEN)
If you need this feature when packaging a desktop app using
flet build, see this.
Toggle semantics debugger
import flet as ft
def main(page: ft.Page):
page.vertical_alignment = ft.MainAxisAlignment.CENTER
page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
def on_keyboard(e: ft.KeyboardEvent):
if e.shift and e.key == "S":
page.show_semantics_debugger = not page.show_semantics_debugger
page.update()
page.on_keyboard_event = on_keyboard
def button_click(e: ft.Event[ft.Button]):
counter.value = str(int(counter.value) + 1)
page.update()
page.add(
ft.SafeArea(
content=ft.Column(
controls=[
counter := ft.Text("0", size=40),
ft.Text("Press Shift+S to toggle semantics debugger"),
ft.Button(
content="Increment number",
icon=ft.Icons.ADD,
on_click=button_click,
),
]
)
)
)
if __name__ == "__main__":
ft.run(main)
Get device locales
import flet as ft
async def main(page: ft.Page):
def format_locales(locales: list[ft.Locale]) -> str:
"""Format locale list for display."""
return ", ".join(str(loc) for loc in locales)
def handle_locale_change(e: ft.LocaleChangeEvent):
page.add(ft.Text(f"Locales changed: {format_locales(e.locales)}"))
page.on_locale_change = handle_locale_change
page.scroll = ft.ScrollMode.AUTO
page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
initial_locales = (await page.get_device_info()).locales
page.add(
ft.SafeArea(
content=ft.Column(
controls=[
ft.Text(f"Initial locales: {format_locales(initial_locales)}"),
ft.Text(
"Change your system or browser language to trigger "
"on_locale_change.",
color=ft.Colors.BLUE,
),
]
)
)
)
if __name__ == "__main__":
ft.run(main)
Properties
authproperty
auth: Optional[Authorization]The current authorization context, or None if the user is not authorized.
browser_context_menuproperty
DEPRECATED: The BrowserContextMenu service for the current page.
client_ipclass-attributeinstance-attribute
client_ip: Optional[str] = NoneIP address of the connected user.
This property is web- and read-only only.
client_user_agentclass-attributeinstance-attribute
client_user_agent: Optional[str] = NoneBrowser details of the connected user.
This property is web- and read-only only.
debugclass-attributeinstance-attribute
debug: bool = FalseTrue if Flutter client of Flet app is running in debug mode.
This property is read-only.
fontsclass-attributeinstance-attribute
fonts: Optional[dict[str, str]] = NoneDefines the custom fonts to be used in the application.
Value is a dictionary, in which the keys represent the font family name used for reference and the values:
- Key: The font family name used for reference.
- Value: The font source, either an absolute URL or a relative path to a
local asset. The following font file formats are supported
.ttc,.ttfand.otf.
Usage example here.
multi_viewclass-attributeinstance-attribute
multi_view: bool = FalseTrue if the application is running with multi-view support.
This property is read-only.
multi_viewsclass-attributeinstance-attribute
multi_views: list[MultiView] = field(default_factory=list)The list of multi-views associated with this page.
platformclass-attributeinstance-attribute
platform: Optional[PagePlatform] = NoneThe operating system the application is running on.
platform_brightnessclass-attributeinstance-attribute
platform_brightness: Optional[Brightness] = NoneThe current brightness mode of the host platform.
This property is read-only.
pwaclass-attributeinstance-attribute
pwa: bool = FalseTrue if the application is running as Progressive Web App (PWA).
This property is read-only.
pyodideclass-attributeinstance-attribute
pyodide: bool = FalseTrue if the application is running in Pyodide (WebAssembly) mode.
This property is read-only.
routeclass-attributeinstance-attribute
route: str = '/'Gets current app route.
This property is read-only.
shared_preferencesproperty
DEPRECATED: The SharedPreferences service for the current page.
storage_pathsproperty
DEPRECATED: The StoragePaths service for the current page.
testclass-attributeinstance-attribute
test: bool = FalseTrue if the application is running with test mode.
This property is read-only.