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.
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.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.
url_launcherproperty
url_launcher: UrlLauncherDEPRECATED: The UrlLauncher service for the current page.
wasmclass-attributeinstance-attribute
wasm: bool = FalseTrue if the application is running in WebAssembly (WASM) mode.
This property is read-only.
webclass-attributeinstance-attribute
web: bool = FalseTrue if the application is running in the web browser.
This property is read-only.
Events
on_app_lifecycle_state_changeclass-attributeinstance-attribute
on_app_lifecycle_state_change: Optional[EventHandler[AppLifecycleStateChangeEvent]] = NoneCalled when app lifecycle state changes.
on_closeclass-attributeinstance-attribute
on_close: Optional[ControlEventHandler[Page]] = NoneCalled when a session has expired after configured amount of time (60 minutes by default).
on_connectclass-attributeinstance-attribute
on_connect: Optional[ControlEventHandler[Page]] = NoneCalled when a web user (re-)connects to a page session.
It is not triggered when an app page is first opened, but is triggered when the page is refreshed, or Flet web client has re-connected after computer was unlocked. This event could be used to detect when a web user becomes "online".
on_disconnectclass-attributeinstance-attribute
on_disconnect: Optional[ControlEventHandler[Page]] = NoneCalled when a web user disconnects from a page session, i.e. closes browser tab/window.
on_errorclass-attributeinstance-attribute
on_error: Optional[ControlEventHandler[Page]] = NoneCalled when unhandled exception occurs.
on_keyboard_eventclass-attributeinstance-attribute
on_keyboard_event: Optional[EventHandler[KeyboardEvent]] = NoneCalled when a keyboard key is pressed.
on_locale_changeclass-attributeinstance-attribute
on_locale_change: Optional[EventHandler[LocaleChangeEvent]] = NoneCalled when the locale preferences/settings of the host platform have changed.
For example, when the user updates device language settings or browser preferred languages.
on_loginclass-attributeinstance-attribute
on_login: Optional[EventHandler[LoginEvent]] = NoneCalled upon successful or failed OAuth authorization flow.
See Authentication guide for more information and examples.
on_logoutclass-attributeinstance-attribute
on_logout: Optional[ControlEventHandler[Page]] = NoneCalled after page.logout() call.
on_multi_view_addclass-attributeinstance-attribute
on_multi_view_add: Optional[EventHandler[MultiViewAddEvent]] = NoneTBD
on_multi_view_removeclass-attributeinstance-attribute
on_multi_view_remove: Optional[EventHandler[MultiViewRemoveEvent]] = NoneTBD
on_platform_brightness_changeclass-attributeinstance-attribute
on_platform_brightness_change: Optional[EventHandler[PlatformBrightnessChangeEvent]] = NoneCalled when brightness of app host platform has changed.
on_route_changeclass-attributeinstance-attribute
on_route_change: Optional[EventHandler[RouteChangeEvent]] = NoneCalled when page route changes either programmatically, by editing application URL or using browser Back/Forward buttons.
on_view_popclass-attributeinstance-attribute
on_view_pop: Optional[EventHandler[ViewPopEvent]] = NoneCalled when the user clicks automatic "Back" button in AppBar control.
Methods
before_event
before_event(e: ControlEvent)can_launch_urlasyncdeprecated
can_launch_url(url: str)Deprecated since version 0.90.0. Use UrlLauncher().can_launch_url() instead.
Checks whether the specified URL can be handled by some app installed on the device.
Parameters:
- url (str) - The URL to check.
Returns:
- bool -
Trueif it is possible to verify that there is a handler available.Falseif there is no handler available, or the application does not have permission to check. For example: - On recent versions of Android and iOS, this will always returnFalseunless the application has been configuration to allow querying the system for launch support. - In web mode, this will always returnFalseexcept for a few specific schemes that are always assumed to be supported (such as http(s)), as web pages are never allowed to query installed applications.
close_in_app_web_viewasyncdeprecated
close_in_app_web_view()Deprecated since version 0.90.0. Use UrlLauncher().close_in_app_web_view() instead.
Closes in-app web view opened with launch_url().
📱 Mobile only.
error
error(message: str)Report an application error to the current session/client.
Parameters:
- message (str) - Error message to send.
get_control
get_control(id: int)Get a control by its id.
def main(page: ft.Page):
x = ft.IconButton(ft.Icons.ADD)
page.add(x)
print(type(page.get_control(x._i)))
get_device_infoasync
get_device_info()Returns device information.
Returns:
- Optional[DeviceInfo] - The device information object for the current platform, or
Noneif unavailable.
get_upload_url
get_upload_url(file_name: str, expires: int)Generates presigned upload URL for built-in upload storage:
file_name- a relative to upload storage path.expires- a URL time-to-live in seconds.
upload_url = page.get_upload_url("dir/filename.ext", 60)
To enable built-in upload storage, provide the upload_dir
argument to ft.run() call:
ft.run(main, upload_dir="uploads")
godeprecated
go(route: str, skip_route_change_event: bool = False, **kwargs: Any = {})Deprecated since version 0.80.0 and scheduled for removal in 0.90.0. Use push_route() instead.
A helper method that updates page.route, calls page.on_route_change event handler to update views and finally calls page.update().
launch_urlasyncdeprecated
launch_url(url: Union[str, Url], web_popup_window_name: Optional[Union[str, UrlTarget]] = None, web_popup_window: bool = False, web_popup_window_width: Optional[int] = None, web_popup_window_height: Optional[int] = None)Deprecated since version 0.90.0. Use UrlLauncher().launch_url() instead.
Opens a web browser or popup window to a given url.
Parameters:
- url (Union[str, Url]) - The URL to open.
- web_popup_window_name (Optional[Union[str, UrlTarget]], default:
None) - Window tab/name to open URL in. Use flet.UrlTarget.SELF for the same browser tab, flet.UrlTarget.BLANK for a new browser tab (or in external application on a mobile device), or a custom name for a named tab. - web_popup_window (bool, default:
False) - Display the URL in a browser popup window. - web_popup_window_width (Optional[int], default:
None) - Popup window width. - web_popup_window_height (Optional[int], default:
None) - Popup window height.
loginasync
login(provider: OAuthProvider, fetch_user: bool = True, fetch_groups: bool = False, scope: Optional[list[str]] = None, saved_token: Optional[str] = None, on_open_authorization_url: Optional[Callable[[str], Coroutine[Any, Any, None]]] = None, complete_page_html: Optional[str] = None, redirect_to_page: Optional[bool] = False, authorization: type[AT] = AuthorizationImpl)Starts OAuth flow.
See Authentication guide for more information and examples.
logout
logout()Clears current authentication context. See Authentication guide for more information and examples.
push_routeasync
push_route(route: str, **kwargs: Any = {})Pushes a new navigation route to the browser history stack.
Changing route will fire page.on_route_change event
handler.
import asyncio
import flet as ft
def main(page: ft.Page):
page.title = "Routes Example"
def route_change():
page.views.clear()
page.views.append(
ft.View(
route="/",
controls=[
ft.AppBar(
title=ft.Text("Flet app"),
),
ft.Button(
"Visit Store",
on_click=lambda: asyncio.create_task(
page.push_route("/store")
),
),
],
)
)
if page.route == "/store":
page.views.append(
ft.View(
route="/store",
controls=[
ft.AppBar(
title=ft.Text("Store"),
),
ft.Button(
"Go Home",
on_click=lambda: asyncio.create_task(
page.push_route("/")
),
),
],
)
)
page.update()
async def view_pop(e):
if e.view is not None:
print("View pop:", e.view)
page.views.remove(e.view)
top_view = page.views[-1]
await page.push_route(top_view.route)
page.on_route_change = route_change
page.on_view_pop = view_pop
route_change()
if __name__ == "__main__":
ft.run(main)
Parameters:
- route (str) - New navigation route.
- **kwargs (default:
{}) - Additional query string parameters to be added to the route.
render
render(component: Callable[..., Union[list[View], View, list[Control], Control]], *args: Any = (), **kwargs: Any = {})Render a component tree into controls of the root view.
The rendered result replaces page.views[0].controls, then triggers
initial page update and component update scheduler startup.
render_views
render_views(component: Callable[..., Union[list[View], View, list[Control], Control]], *args: Any = (), **kwargs: Any = {})Render a component tree as the full list of page views.
The rendered result replaces page.views, then triggers initial page
update and component update scheduler startup.
run_task
run_task(handler: Callable[InputT, Awaitable[RetT]], *args: InputT.args = (), **kwargs: InputT.kwargs = {})Run handler coroutine as a new Task in the event loop associated with the current page.
run_thread
run_thread(handler: Callable[InputT, Any], *args: InputT.args = (), **kwargs: InputT.kwargs = {})Run handler function as a new Thread in the executor associated with the current page.
set_allowed_device_orientationsasync
set_allowed_device_orientations(orientations: list[DeviceOrientation])Constrains the allowed orientations for the app when running on a mobile device.
Parameters:
- orientations (list[DeviceOrientation]) - A list of allowed device orientations. Set to an empty list to use the system default behavior.
Raises:
- FletUnsupportedPlatformException - If the method is called on a non-mobile platform.
Limitations:
Android: On Android 16 (API 36) or later, this method won't be able to change the orientation of devices with a display width ≥ 600 dp cannot change orientation. For more details see Android 16 docs here. Also, Android limits the orientations to the following combinations:
[]→unspecified[PORTRAIT_UP]→portrait[LANDSCAPE_LEFT]→landscape[PORTRAIT_DOWN]→reversePortrait[PORTRAIT_UP, PORTRAIT_DOWN]→userPortrait[LANDSCAPE_RIGHT]→reverseLandscape[LANDSCAPE_LEFT, LANDSCAPE_RIGHT]→userLandscape[PORTRAIT_UP, LANDSCAPE_LEFT, LANDSCAPE_RIGHT]→user[PORTRAIT_UP, PORTRAIT_DOWN, LANDSCAPE_LEFT, LANDSCAPE_RIGHT]→fullUser
- iOS: This setting will only be respected on iPad if multitasking is disabled. You can decide to opt out of multitasking on iPad, then this will work but your app will not support Slide Over and Split View multitasking anymore. Should you decide to opt out of multitasking you can do this by setting "Requires full screen" to true in the Xcode Deployment Info.