Skip to main content

Overview

Page is a container for View controls. A page instance and the root view are automatically created when a new user session starts. Source: flet.controls.page:344

Class Signature

from flet import Page

class Page(BasePage):
    """Page is a container for View controls."""

Properties

Session and Connection

session
Session
The session that this page belongs to. Read-only property.Source: page.py:1106
query
QueryString
The query parameters of the current page. Read-only property.Source: page.py:1115
url
Optional[str]
The URL of the current page. Read-only property.Source: page.py:1122
name
str
The name of the current page. Read-only property.Source: page.py:1129
loop
asyncio.AbstractEventLoop
The event loop for the current page. Read-only property.Source: page.py:1136
executor
Optional[ThreadPoolExecutor]
The executor for the current page. Read-only property.Source: page.py:1143

Page State

route
str
default:"/"
Gets current app route. Read-only property.Source: page.py:369
web
bool
default:"False"
True if the application is running in the web browser. Read-only property.Source: page.py:377
pwa
bool
default:"False"
True if the application is running as Progressive Web App (PWA). Read-only property.Source: page.py:385
debug
bool
default:"False"
True if Flutter client of Flet app is running in debug mode. Read-only property.Source: page.py:392
wasm
bool
default:"False"
True if the application is running in WebAssembly (WASM) mode. Read-only property.Source: page.py:400
test
bool
default:"False"
True if the application is running with test mode. Read-only property.Source: page.py:408
multi_view
bool
default:"False"
True if the application is running with multi-view support. Read-only property.Source: page.py:416
pyodide
bool
default:"False"
True if the application is running in Pyodide (WebAssembly) mode. Read-only property.Source: page.py:424

Platform and Device

platform
Optional[PagePlatform]
The operating system the application is running on.Source: page.py:456
platform_brightness
Optional[Brightness]
The current brightness mode of the host platform. Read-only property.Source: page.py:432
client_ip
Optional[str]
IP address of the connected user. Web-only, read-only property.Source: page.py:440
client_user_agent
Optional[str]
Browser details of the connected user. Web-only, read-only property.Source: page.py:448

Multi-View

multi_views
list[MultiView]
default:"[]"
The list of multi-views associated with this page.Source: page.py:358
window
Window
Provides properties/methods/events to monitor and control the app’s native OS window.Source: page.py:363

Customization

fonts
Optional[dict[str, str]]
Defines the custom fonts to be used in the application.Value is a dictionary where:
  • Key: The font family name used for reference
  • Value: The font source (absolute URL or relative path to local asset)
Supported formats: .ttc, .ttf, .otfSource: page.py:461
page.fonts = {
    "Kanit": "https://raw.githubusercontent.com/google/fonts/master/ofl/kanit/Kanit-Bold.ttf",
    "Open Sans": "/fonts/OpenSans-Regular.ttf"
}

Authentication

auth
Optional[Authorization]
The current authorization context, or None if the user is not authorized. Read-only property.Source: page.py:1150
pubsub
PubSubClient
The PubSub client for the current page. Read-only property.Source: page.py:1157

Events

on_route_change
Optional[EventHandler[RouteChangeEvent]]
Called when page route changes either programmatically, by editing application URL or using browser Back/Forward buttons.Source: page.py:497
def route_change_handler(e: ft.RouteChangeEvent):
    print(f"Route changed to: {e.route}")

page.on_route_change = route_change_handler
on_view_pop
Optional[EventHandler[ViewPopEvent]]
Called when the user clicks automatic “Back” button in AppBar control.Source: page.py:503
async def view_pop(e: ft.ViewPopEvent):
    print(f"View popped: {e.route}")
    if e.view is not None:
        page.views.remove(e.view)

page.on_view_pop = view_pop

Platform Events

on_platform_brightness_change
Optional[EventHandler[PlatformBrightnessChangeEvent]]
Called when brightness of app host platform has changed.Source: page.py:475
on_locale_change
Optional[EventHandler[LocaleChangeEvent]]
Called when the locale preferences/settings of the host platform have changed. For example, when the user updates device language settings or browser preferred languages.Source: page.py:482
on_app_lifecycle_state_change
Optional[EventHandler[AppLifecycleStateChangeEvent]]
Called when app lifecycle state changes.Source: page.py:490

Input Events

on_keyboard_event
Optional[EventHandler[KeyboardEvent]]
Called when a keyboard key is pressed.Source: page.py:508
def keyboard_handler(e: ft.KeyboardEvent):
    print(f"Key: {e.key}, Ctrl: {e.ctrl}, Shift: {e.shift}")

page.on_keyboard_event = keyboard_handler

Connection Events

on_connect
Optional[ControlEventHandler[Page]]
Called when a web user (re-)connects to a page session. Not triggered when an app page is first opened, but triggered when the page is refreshed or Flet web client has re-connected.Source: page.py:513
on_disconnect
Optional[ControlEventHandler[Page]]
Called when a web user disconnects from a page session, i.e., closes browser tab/window.Source: page.py:523
on_close
Optional[ControlEventHandler[Page]]
Called when a session has expired after configured amount of time (60 minutes by default).Source: page.py:529
on_error
Optional[ControlEventHandler[Page]]
Called when unhandled exception occurs.Source: page.py:548

Authentication Events

on_login
Optional[EventHandler[LoginEvent]]
Called upon successful or failed OAuth authorization flow.Source: page.py:535
async def handle_login(e: ft.LoginEvent):
    if e.error:
        print(f"Login failed: {e.error}")
    else:
        print("Login successful")

page.on_login = handle_login
on_logout
Optional[ControlEventHandler[Page]]
Called after page.logout() call.Source: page.py:543

Multi-View Events

on_multi_view_add
Optional[EventHandler[MultiViewAddEvent]]
Called when a new multi-view is created.Source: page.py:553
on_multi_view_remove
Optional[EventHandler[MultiViewRemoveEvent]]
Called when a multi-view is removed.Source: page.py:558

Methods

Control Management

get_control
(id: int) -> Optional[BaseControl]
Get a control by its internal ID.Source: page.py:576Parameters:
  • id (int): Internal control ID
Returns: Control instance or None if not found
x = ft.IconButton(ft.Icons.ADD)
page.add(x)
control = page.get_control(x._i)
update
(*controls: Control) -> None
Push pending state changes to the client.Source: page.py:655Parameters:
  • *controls: Specific controls to patch. When omitted, patches the whole page state.
# Update entire page
page.update()

# Update specific controls
page.update(text1, text2)
error
(message: str) -> None
Report an application error to the current session/client.Source: page.py:691Parameters:
  • message (str): Error message to send
page.error("Failed to load data")

Component Rendering

render
(component: Callable[..., Union[list[View], View, list[Control], Control]], *args, **kwargs) -> None
Render a component tree into controls of the root view. The rendered result replaces page.views[0].controls.Source: page.py:590Parameters:
  • component: Component function to render
  • *args: Positional arguments passed to component
  • **kwargs: Keyword arguments passed to component
def my_component():
    return ft.Text("Hello, World!")

page.render(my_component)
render_views
(component: Callable[..., Union[list[View], View, list[Control], Control]], *args, **kwargs) -> None
Render a component tree as the full list of page views. The rendered result replaces page.views.Source: page.py:613Parameters:
  • component: Component function to render
  • *args: Positional arguments passed to component
  • **kwargs: Keyword arguments passed to component
schedule_update
() -> None
Queue this page for a deferred batched update.Source: page.py:648

Threading and Async

run_task
(handler: Callable[InputT, Awaitable[RetT]], *args, **kwargs) -> Future[RetT]
Run handler coroutine as a new Task in the event loop associated with the current page.Source: page.py:717Parameters:
  • handler: Coroutine function to run
  • *args: Positional arguments for handler
  • **kwargs: Keyword arguments for handler
Returns: Future for the task resultRaises:
  • TypeError: If handler is not a coroutine function
async def async_operation():
    await asyncio.sleep(1)
    return "Done"

future = page.run_task(async_operation)
run_thread
(handler: Callable[InputT, Any], *args, **kwargs) -> None
Run handler function as a new Thread in the executor associated with the current page.Source: page.py:779Parameters:
  • handler: Function to run in thread
  • *args: Positional arguments for handler
  • **kwargs: Keyword arguments for handler
def blocking_operation():
    import time
    time.sleep(5)
    print("Done")

page.run_thread(blocking_operation)
push_route
async (route: str, **kwargs: Any) -> None
Pushes a new navigation route to the browser history stack. Changing route will fire page.on_route_change event handler.Source: page.py:817Parameters:
  • route (str): New navigation route
  • **kwargs: Additional query string parameters to be added to the route
await page.push_route("/store")
await page.push_route("/product", id=123)

Upload

get_upload_url
(file_name: str, expires: int) -> str
Generates presigned upload URL for built-in upload storage.Source: page.py:898Parameters:
  • file_name (str): Relative path to upload storage
  • expires (int): URL time-to-live in seconds
Returns: Presigned upload URL
upload_url = page.get_upload_url("dir/filename.ext", 60)
To enable built-in upload storage, provide upload_dir to ft.run():
ft.run(main, upload_dir="uploads")

Authentication

login
async (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]] = None, complete_page_html: Optional[str] = None, redirect_to_page: Optional[bool] = False, authorization: type[AT] = AuthorizationImpl) -> AT
Starts OAuth flow.Source: page.py:919Parameters:
  • provider (OAuthProvider): OAuth provider configuration
  • fetch_user (bool): Whether to fetch user information
  • fetch_groups (bool): Whether to fetch user groups
  • scope (Optional[list[str]]): OAuth scopes to request
  • saved_token (Optional[str]): Previously saved token to rehydrate
  • on_open_authorization_url (Optional[Callable]): Custom handler for authorization URL
  • complete_page_html (Optional[str]): Custom HTML for completion page
  • redirect_to_page (Optional[bool]): Redirect back to page after auth
  • authorization (type[AT]): Authorization implementation class
Returns: Authorization instance
from flet.auth.providers import GoogleOAuthProvider

provider = GoogleOAuthProvider(
    client_id="your-client-id",
    client_secret="your-secret",
    redirect_url="http://localhost:8000/oauth_callback"
)

auth = await page.login(provider)
logout
() -> None
Clears current authentication context.Source: page.py:1016
page.logout()

Device Information

get_device_info
async () -> Optional[DeviceInfo]
Returns device information.Source: page.py:1213Returns: Device information object for the current platform, or None if unavailableReturn types:
  • WebDeviceInfo for web
  • AndroidDeviceInfo for Android
  • IosDeviceInfo for iOS
  • MacOsDeviceInfo for macOS
  • LinuxDeviceInfo for Linux
  • WindowsDeviceInfo for Windows
device_info = await page.get_device_info()
if device_info:
    print(f"Platform: {device_info.platform}")
set_allowed_device_orientations
async (orientations: list[DeviceOrientation]) -> None
Constrains the allowed orientations for the app when running on a mobile device.Source: page.py:1238Parameters:
  • orientations (list[DeviceOrientation]): List of allowed device orientations. Set to empty list to use system default.
Raises:
  • FletUnsupportedPlatformException: If called on non-mobile platform
Limitations:
  • Android: On Android 16+ with displays ≥600dp width, orientation cannot be changed. Android limits orientation combinations.
  • iOS: Only respected on iPad if multitasking is disabled
from flet import DeviceOrientation

await page.set_allowed_device_orientations([
    DeviceOrientation.PORTRAIT_UP,
    DeviceOrientation.LANDSCAPE_LEFT
])

Deprecated Methods

The following methods are deprecated and will be removed in future versions.
go
(route: str, skip_route_change_event: bool = False, **kwargs: Any) -> None
DEPRECATED: Use push_route() instead.Deprecated in version 0.80.0, will be removed in 0.90.0.Source: page.py:800
launch_url
async (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) -> None
DEPRECATED: Use UrlLauncher().launch_url() instead.Deprecated in version 0.90.0.Source: page.py:1032
can_launch_url
async (url: str) -> bool
DEPRECATED: Use UrlLauncher().can_launch_url() instead.Deprecated in version 0.90.0.Source: page.py:1070
close_in_app_web_view
async () -> None
DEPRECATED: Use UrlLauncher().close_in_app_web_view() instead.Deprecated in version 0.90.0.Source: page.py:1097

Usage Examples

Basic Page Setup

import flet as ft

def main(page: ft.Page):
    page.title = "My Flet App"
    page.theme_mode = ft.ThemeMode.DARK
    page.padding = 20
    
    page.add(
        ft.Text("Hello, World!", size=30)
    )

ft.run(main)
import flet as ft
import asyncio

def main(page: ft.Page):
    def route_change(e: ft.RouteChangeEvent):
        page.views.clear()
        
        # Home page
        page.views.append(
            ft.View(
                route="/",
                controls=[
                    ft.AppBar(title=ft.Text("Home")),
                    ft.ElevatedButton(
                        "Go to Settings",
                        on_click=lambda _: asyncio.create_task(
                            page.push_route("/settings")
                        )
                    )
                ]
            )
        )
        
        # Settings page
        if page.route == "/settings":
            page.views.append(
                ft.View(
                    route="/settings",
                    controls=[
                        ft.AppBar(title=ft.Text("Settings")),
                        ft.Text("Settings Page")
                    ]
                )
            )
        
        page.update()
    
    page.on_route_change = route_change
    page.on_view_pop = lambda e: asyncio.create_task(
        page.push_route(page.views[-2].route if len(page.views) > 1 else "/")
    )
    
    route_change(None)

ft.run(main)

Using Threading

import flet as ft
import time

def main(page: ft.Page):
    progress = ft.ProgressBar()
    status = ft.Text()
    
    def long_running_task():
        for i in range(5):
            time.sleep(1)
            status.value = f"Processing... {i+1}/5"
            page.update()
        status.value = "Complete!"
        page.update()
    
    def start_task(e):
        page.run_thread(long_running_task)
    
    page.add(
        progress,
        status,
        ft.ElevatedButton("Start Task", on_click=start_task)
    )

ft.run(main)

OAuth Authentication

import flet as ft
from flet.auth.providers import GoogleOAuthProvider

async def main(page: ft.Page):
    provider = GoogleOAuthProvider(
        client_id="your-client-id.apps.googleusercontent.com",
        client_secret="your-client-secret",
        redirect_url="http://localhost:8000/oauth_callback"
    )
    
    async def login_click(e):
        await page.login(provider)
    
    async def handle_login(e: ft.LoginEvent):
        if e.error:
            page.add(ft.Text(f"Login failed: {e.error}", color="red"))
        else:
            user = page.auth.user
            page.add(ft.Text(f"Welcome, {user.name}!"))
        page.update()
    
    page.on_login = handle_login
    
    page.add(
        ft.ElevatedButton("Login with Google", on_click=login_click)
    )

ft.run(main)

See Also

  • BasePage - Base class for Page
  • [View(/api/page) - View component for navigation
  • Control - Base control class
  • app() and run() - App lifecycle functions

Build docs developers (and LLMs) love