### Flet GitHub OAuth Authentication Example Source: https://docs.flet.dev/cookbook/authentication?q= A complete Flet application example demonstrating how to implement GitHub OAuth authentication. It includes setting up the provider, handling login/logout buttons, and managing authentication state changes. ```python import os import flet as ft from flet.auth.providers import GitHubOAuthProvider def main(page: ft.Page): provider = GitHubOAuthProvider( client_id=os.getenv("GITHUB_CLIENT_ID"), client_secret=os.getenv("GITHUB_CLIENT_SECRET"), redirect_url="http://localhost:8550/oauth_callback", ) def login_button_click(e): page.login(provider, scope=["public_repo"]) def on_login(e: ft.LoginEvent): if not e.error: toggle_login_buttons() def logout_button_click(e): page.logout() def on_logout(e): toggle_login_buttons() def toggle_login_buttons(): login_button.visible = page.auth is None logout_button.visible = page.auth is not None page.update() login_button = ft.Button("Login with GitHub", on_click=login_button_click) logout_button = ft.Button("Logout", on_click=logout_button_click) toggle_login_buttons() page.on_login = on_login page.on_logout = on_logout page.add(login_button, logout_button) ft.run(main, port=8550, view=ft.AppView.WEB_BROWSER) ``` -------------------------------- ### Flet Multi-View Routing Example Source: https://docs.flet.dev/cookbook/navigation-and-routing A comprehensive example demonstrating Flet's routing system. It clears and rebuilds the view stack based on the current route, handling navigation between different screens like '/', '/settings', and '/settings/mail'. It also implements view popping for back navigation. ```python import flet as ft def main(page: ft.Page): page.title = "Routes Example" print("Initial route:", page.route) async def open_mail_settings(e): await page.push_route("/settings/mail") async def open_settings(e): await page.push_route("/settings") def route_change(): print("Route change:", page.route) page.views.clear() page.views.append( ft.View( route="/", controls=[ ft.AppBar(title=ft.Text("Flet app")), ft.Button("Go to settings", on_click=open_settings), ], ) ) if page.route == "/settings" or page.route == "/settings/mail": page.views.append( ft.View( route="/settings", controls=[ ft.AppBar( title=ft.Text("Settings"), bgcolor=ft.Colors.SURFACE_CONTAINER_HIGHEST, ), ft.Text("Settings!", theme_style=ft.TextThemeStyle.BODY_MEDIUM), ft.Button( content="Go to mail settings", on_click=open_mail_settings, ), ], ) ) if page.route == "/settings/mail": page.views.append( ft.View( route="/settings/mail", controls=[ ft.AppBar( title=ft.Text("Mail Settings"), bgcolor=ft.Colors.SURFACE_CONTAINER_HIGHEST, ), ft.Text("Mail settings!"), ], ) ) 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) ``` -------------------------------- ### Advanced Keyboard Event Example Source: https://docs.flet.dev/cookbook/keyboard-shortcuts A more advanced example showcasing how to visually represent keyboard input and modifier key states using custom controls. ```APIDOC ## Advanced Keyboard Event Visualization ### Description This example demonstrates a more complex use case of `page.on_keyboard_event` by visually updating custom controls to reflect the pressed key and the active modifier keys (Shift, Ctrl, Alt, Meta). ### Method Assign a function to `page.on_keyboard_event` that updates the properties of UI elements based on the `KeyboardEvent` object. ### Endpoint N/A (This is a client-side event handler) ### Parameters #### Event Handler Parameter (`e`) - **key** (string) - The textual representation of the pressed key. - **shift** (boolean) - `True` if the "Shift" key was pressed. - **ctrl** (boolean) - `True` if the "Control" key was pressed. - **alt** (boolean) - `True` if the "Alt" ("Option") key was pressed. - **meta** (boolean) - `True` if the "Command" key was pressed. ### Request Example ```python 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.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, ), ) ft.run(main) ``` ### Response #### Success Response When a key is pressed, the `on_keyboard` function updates the text of the `key` control and toggles the visibility of the modifier key controls based on the event data. The page is then updated to reflect these changes. #### Response Example (Visual update of controls on the UI. For example, if 'A' is pressed with Shift, the 'key' control shows 'A', and the 'Shift' control becomes visible.) ``` -------------------------------- ### Flet GitHub OAuth Authentication Example Source: https://docs.flet.dev/cookbook/authentication A complete Flet application example demonstrating how to implement GitHub OAuth authentication. It includes setting up the GitHub provider, handling login and logout button clicks, and managing the UI based on authentication status via `page.on_login` and `page.on_logout` event handlers. ```python import os import flet as ft from flet.auth.providers import GitHubOAuthProvider def main(page: ft.Page): provider = GitHubOAuthProvider( client_id=os.getenv("GITHUB_CLIENT_ID"), client_secret=os.getenv("GITHUB_CLIENT_SECRET"), redirect_url="http://localhost:8550/oauth_callback", ) def login_button_click(e): page.login(provider, scope=["public_repo"]) def on_login(e: ft.LoginEvent): if not e.error: toggle_login_buttons() def logout_button_click(e): page.logout() def on_logout(e): toggle_login_buttons() def toggle_login_buttons(): login_button.visible = page.auth is None logout_button.visible = page.auth is not None page.update() login_button = ft.Button("Login with GitHub", on_click=login_button_click) logout_button = ft.Button("Logout", on_click=logout_button_click) toggle_login_buttons() page.on_login = on_login page.on_logout = on_logout page.add(login_button, logout_button) ft.run(main, port=8550, view=ft.AppView.WEB_BROWSER) ``` -------------------------------- ### Launch Android Settings via Subprocess Source: https://docs.flet.dev/cookbook/subprocess?q= Demonstrates how to trigger an external Android activity using the am start command. It uses subprocess.run with a list of arguments to ensure safe execution. ```python import subprocess import flet as ft def main(page: ft.Page): def open_settings(e): result = subprocess.run( ["am", "start", "-n", "com.android.settings/.Settings", "--user", "0"], shell=False, capture_output=True, text=True, ) print("STDOUT:", result.stdout) print("STDERR:", result.stderr) page.add( ft.SafeArea( content=ft.Button("Open Settings app", on_click=open_settings) ) ) ft.run(main) ``` -------------------------------- ### Equal expansion of controls Source: https://docs.flet.dev/cookbook/expanding-controls This example demonstrates how to split available horizontal space equally between two containers in a Row by setting expand=True on both. ```python import flet as ft def main(page: ft.Page): page.add( ft.Container( width=500, height=180, padding=10, border=ft.Border.all(2, ft.Colors.BLUE_GREY_200), border_radius=10, content=ft.Row( spacing=8, controls=[ ft.Container(expand=True, bgcolor=ft.Colors.ORANGE_300, border_radius=8, alignment=ft.Alignment.CENTER, content=ft.Text("Card 1")), ft.Container(expand=True, bgcolor=ft.Colors.GREEN_200, border_radius=8, alignment=ft.Alignment.CENTER, content=ft.Text("Card 2")), ], ), ) ) if __name__ == "__main__": ft.run(main) ``` -------------------------------- ### Sign in with GitHub OAuth Source: https://docs.flet.dev/cookbook/authentication Example code demonstrating how to implement a 'Login with GitHub' button in a Flet application using the GitHubOAuthProvider. ```APIDOC ## Sign in with OAuth provider ### Description This example demonstrates how to integrate GitHub OAuth for user authentication in a Flet application. It covers configuring the `GitHubOAuthProvider` with client ID and secret, initiating the login flow, and handling the login event to retrieve user details and access tokens. ### Method `page.login(provider)` ### Endpoint `/oauth_callback` (handled internally by Flet) ### Parameters #### Environment Variables - **GITHUB_CLIENT_ID** (string) - Required - Your GitHub OAuth application's Client ID. - **GITHUB_CLIENT_SECRET** (string) - Required - Your GitHub OAuth application's Client Secret. #### Request Body Not applicable for initiating the login flow. ### Request Example ```python import os import flet as ft from flet.auth.providers import GitHubOAuthProvider GITHUB_CLIENT_ID = os.getenv("GITHUB_CLIENT_ID") assert GITHUB_CLIENT_ID, "set GITHUB_CLIENT_ID environment variable" GITHUB_CLIENT_SECRET = os.getenv("GITHUB_CLIENT_SECRET") assert GITHUB_CLIENT_SECRET, "set GITHUB_CLIENT_SECRET environment variable" def main(page: ft.Page): provider = GitHubOAuthProvider( client_id=GITHUB_CLIENT_ID, client_secret=GITHUB_CLIENT_SECRET, redirect_url="http://localhost:8550/oauth_callback", ) def login_click(e): page.login(provider) def on_login(e): print("Login error:", e.error) print("Access token:", page.auth.token.access_token) print("User ID:", page.auth.user.id) page.on_login = on_login page.add(ft.Button("Login with GitHub", on_click=login_click)) ft.run(main, port=8550, view=ft.WEB_BROWSER) ``` ### Response #### Success Response (on_login event) - **e.error** (string) - Description of any login error, null if successful. - **page.auth.token.access_token** (string) - The access token obtained from the OAuth provider. - **page.auth.user.id** (string) - The unique identifier of the logged-in user. #### Response Example (console output) ``` Login error: None Access token: ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxx User ID: 12345678 ``` ### Caution - Ensure that your GitHub OAuth application's **Authorization callback URL** is correctly set to `{application-url}/oauth_callback`. - Never embed secrets (Client ID, Client Secret) directly into your source code. Use environment variables instead. - Set environment variables before running the app: ```bash $ export GITHUB_CLIENT_ID="" $ export GITHUB_CLIENT_SECRET="" ``` - If running on a fixed port, specify it using the `port` argument in `flet.run()` (e.g., `port=8550`). ``` -------------------------------- ### Launch Android Settings App via Subprocess Source: https://docs.flet.dev/cookbook/subprocess Demonstrates how to trigger an external Android activity using the 'am start' command. It uses subprocess.run with a list of arguments for security and captures output for debugging. ```python import subprocess import flet as ft def main(page: ft.Page): def open_settings(e): result = subprocess.run( ["am", "start", "-n", "com.android.settings/.Settings", "--user", "0"], shell=False, capture_output=True, text=True, ) print("STDOUT:", result.stdout) print("STDERR:", result.stderr) page.add( ft.SafeArea( content=ft.Button("Open Settings app", on_click=open_settings) ) ) ft.run(main) ``` -------------------------------- ### Flet Basic Route Display Source: https://docs.flet.dev/cookbook/navigation-and-routing Demonstrates how to display the initial route of a Flet application. This is a foundational example for understanding how Flet handles routes. ```python import flet as ft def main(page: ft.Page): page.add(ft.Text(f"Initial route: {page.route}")) if __name__ == "__main__": ft.run(main) ``` -------------------------------- ### Proportional space distribution with expand integers Source: https://docs.flet.dev/cookbook/expanding-controls This example shows how to divide available space in a Row proportionally among multiple containers using integer values for the expand property, resulting in a 20%/60%/20% layout. ```python import flet as ft def main(page: ft.Page): page.add( ft.Container( width=500, padding=10, border=ft.Border.all(2, ft.Colors.BLUE_GREY_200), border_radius=10, content=ft.Row( spacing=8, controls=[ ft.Container(expand=1, height=60, bgcolor=ft.Colors.CYAN_300, alignment=ft.Alignment.CENTER, border_radius=8, content=ft.Text("1")), ft.Container(expand=3, height=60, bgcolor=ft.Colors.AMBER_300, alignment=ft.Alignment.CENTER, border_radius=8, content=ft.Text("3")), ft.Container(expand=1, height=60, bgcolor=ft.Colors.PINK_200, alignment=ft.Alignment.CENTER, border_radius=8, content=ft.Text("1")), ], ), ) ) if __name__ == "__main__": ft.run(main) ``` -------------------------------- ### Accessing Asset Files in Production Source: https://docs.flet.dev/cookbook/assets?q= This example shows how to access asset files, such as JSON configuration files, using an absolute path derived from the `FLET_ASSETS_DIR` environment variable, which is set in production builds. ```APIDOC ## Accessing Asset Files in Production ### Description This example demonstrates how to access non-UI asset files (like JSON) using an absolute path. It utilizes the `FLET_ASSETS_DIR` environment variable, which Flet sets in production builds, and includes a fallback for local development. ### Method `ft.run()` ### Endpoint N/A (Local file access) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python import json import os from pathlib import Path import flet as ft def get_assets_dir() -> Path: default_assets_dir = Path(__file__).parent / "assets" # fallback for local runs return Path(os.environ.get("FLET_ASSETS_DIR", str(default_assets_dir))).resolve() def main(page: ft.Page): assets_dir = get_assets_dir() # load a JSON file with (assets_dir / "data" / "some_config.json").open() as f: config = json.load(f) page.add(ft.Text(f"Loaded profile: {config['profile_name']}")) ft.run(main, assets_dir="assets") ``` ### Response #### Success Response (200) - **config** (dict) - Loaded JSON configuration data. #### Response Example ```json { "profile_name": "Example Profile" } ``` ``` -------------------------------- ### Configure Custom OAuth Provider Source: https://docs.flet.dev/cookbook/authentication Example of setting up a custom OAuth provider, such as LinkedIn, by specifying endpoints, scopes, and user identification functions. ```python import os import flet from flet import Button, Page from flet.auth import OAuthProvider def main(page: Page): provider = OAuthProvider( client_id=os.getenv("LINKEDIN_CLIENT_ID"), client_secret=os.getenv("LINKEDIN_CLIENT_SECRET"), authorization_endpoint="https://www.linkedin.com/oauth/v2/authorization", token_endpoint="https://www.linkedin.com/oauth/v2/accessToken", user_endpoint="https://api.linkedin.com/v2/me", user_scopes=["r_liteprofile", "r_emailaddress"], user_id_fn=lambda u: u["id"], redirect_url="http://localhost:8550/oauth_callback", ) def login_click(e): page.login(provider) def on_login(e): if e.error: raise RuntimeError(e.error) print("User ID:", page.auth.user.id) print("Access token:", page.auth.token.access_token) page.on_login = on_login page.add(Button("Login with LinkedIn", on_click=login_click)) flet.app(main, port=8550, view=flet.WEB_BROWSER) ``` -------------------------------- ### Advanced Drag and Drop with Visual Feedback Source: https://docs.flet.dev/cookbook/drag-and-drop Extends the basic drag-and-drop example by adding visual cues. It uses 'content_when_dragging' and 'content_feedback' for custom appearance, and 'on_will_accept'/'on_leave' to highlight the target when a valid drag enters its area. ```python import flet as ft def main(page: ft.Page): page.title = "Drag and Drop example 2" def drag_accept(e): src = page.get_control(e.src_id) src.content.content.value = "0" src.group = "" e.control.content.content.value = "1" e.control.content.border = None page.update() def drag_will_accept(e): e.control.content.border = ft.border.all( 2, ft.Colors.BLACK_45 if e.data == "true" else ft.Colors.RED ) e.control.update() def drag_leave(e): e.control.content.border = None e.control.update() page.add( ft.Row( [ ft.Draggable( group="number", content=ft.Container( width=50, height=50, bgcolor=ft.Colors.CYAN_200, border_radius=5, content=ft.Text("1", size=20), alignment=ft.alignment.center, ), content_when_dragging=ft.Container( width=50, height=50, bgcolor=ft.Colors.BLUE_GREY_200, border_radius=5, ), content_feedback=ft.Text("1"), ) ] ) ) ``` -------------------------------- ### Retrieving All Keys with a Prefix in Flet Storage Source: https://docs.flet.dev/cookbook/client-storage?q= Demonstrates how to fetch all keys from Flet's client storage that start with a specified prefix using `shared_preferences.get_keys()`. This is useful for managing related settings. ```Python await page.shared_preferences.get_keys("key-prefix.") ``` -------------------------------- ### Create an Adaptive Flet Application Source: https://docs.flet.dev/cookbook/adaptive-apps This example demonstrates how to enable adaptive mode for an entire Flet application by setting 'page.adaptive = True'. This configuration automatically adjusts the styling of components like the AppBar and NavigationBar to match the native platform. ```python import flet as ft def main(page): page.adaptive = True page.appbar = ft.AppBar( leading=ft.TextButton("New", style=ft.ButtonStyle(padding=0)), title=ft.Text("Adaptive AppBar"), actions=[ft.IconButton(ft.cupertino_icons.ADD, style=ft.ButtonStyle(padding=0))], bgcolor=ft.Colors.with_opacity(0.04, ft.CupertinoColors.SYSTEM_BACKGROUND), ) page.navigation_bar = ft.NavigationBar( destinations=[ ft.NavigationBarDestination(icon=ft.Icons.EXPLORE, label="Explore"), ft.NavigationBarDestination(icon=ft.Icons.COMMUTE, label="Commute"), ft.NavigationBarDestination(icon=ft.Icons.BOOKMARK_BORDER, selected_icon=ft.Icons.BOOKMARK, label="Bookmark"), ], border=ft.Border(top=ft.BorderSide(color=ft.CupertinoColors.SYSTEM_GREY2, width=0)), ) page.add(ft.SafeArea(ft.Column([ ft.Checkbox(value=False, label="Dark Mode"), ft.Text("First field:"), ft.TextField(keyboard_type=ft.KeyboardType.TEXT), ft.Text("Second field:"), ft.TextField(keyboard_type=ft.KeyboardType.TEXT), ft.Switch(label="A switch"), ft.FilledButton(content=ft.Text("Adaptive button")), ft.Text("Text line 1"), ft.Text("Text line 2"), ft.Text("Text line 3"), ]))) ft.run(main) ``` -------------------------------- ### Implement Chat Application with Flet PubSub Source: https://docs.flet.dev/cookbook/pub-sub?q= This example demonstrates a basic chat application where user messages are broadcast to all active sessions. It uses page.pubsub.subscribe to listen for incoming messages and page.pubsub.send_all to distribute user input. ```python import flet as ft def main(page: ft.Page): page.title = "Flet Chat" # subscribe to broadcast messages def on_message(msg): messages.controls.append(ft.Text(msg)) page.update() page.pubsub.subscribe(on_message) def send_click(e): page.pubsub.send_all(f"{user.value}: {message.value}") # clean up the form message.value = "" page.update() messages = ft.Column() user = ft.TextField(hint_text="Your name", width=150) message = ft.TextField(hint_text="Your message...", expand=True) send = ft.ElevatedButton("Send", on_click=send_click) page.add(messages, ft.Row(controls=[user, message, send])) ft.app(target=main, view=ft.AppView.WEB_BROWSER) ``` -------------------------------- ### Displaying a Local Image Source: https://docs.flet.dev/cookbook/assets?q= This example demonstrates how to display a local image file within your Flet application by placing it in an assets directory and referencing it using a relative path. ```APIDOC ## Displaying a Local Image ### Description This example shows how to include and display an image file from a local assets directory in your Flet app. The `assets_dir` parameter in `ft.run()` specifies the root folder for assets. ### Method `ft.run()` ### Endpoint N/A (Local file access) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python import flet as ft def main(page: ft.Page): page.add( ft.Image(src="images/sample.png") ) ft.run(main, assets_dir="assets") ``` ### Response #### Success Response (200) N/A (UI rendering) #### Response Example N/A ``` -------------------------------- ### Implement View Navigation and Pop Confirmation in Flet Source: https://docs.flet.dev/cookbook/navigation-and-routing This example demonstrates how to manage navigation between views using page.on_view_pop and how to block back navigation using can_pop=False combined with an AlertDialog to request user confirmation before closing a view. ```python import flet as ft def main(page: ft.Page): page.title = "Routes Example" def route_change(): page.views.clear() page.views.append(MainView("/")) if page.route == "/store": page.views.append(PermissionView("/store")) page.update() async def view_pop(e: ft.ViewPopEvent): 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() class MainView(ft.View): def __init__(self, path): super().__init__( route=path, appbar=ft.AppBar(title=ft.Text("Flet app")), controls=[ ft.Button("Go to store", on_click=self.open_store), ], ) async def open_store(self, e): await self.page.push_route("/store") class PermissionView(ft.View): def __init__(self, path): super().__init__( route=path, appbar=ft.AppBar(title=ft.Text(f"{path} View")), can_pop=False, on_confirm_pop=self.ask_pop_permission, ) async def ask_pop_permission(self, e): async def on_dlg_yes(e): self.page.pop_dialog() await self.confirm_pop(True) async def on_dlg_no(e): self.page.pop_dialog() await self.confirm_pop(False) dlg_modal = ft.AlertDialog( title=ft.Text("Please confirm"), content=ft.Text("Go home?"), actions=[ ft.TextButton("Yes", on_click=on_dlg_yes), ft.TextButton("No", on_click=on_dlg_no), ], actions_alignment=ft.MainAxisAlignment.END, on_dismiss=lambda e: print("Modal dialog dismissed!"), ) self.page.show_dialog(dlg_modal) if __name__ == "__main__": ft.run(main) ``` -------------------------------- ### Sign in with GitHub OAuth Provider Source: https://docs.flet.dev/cookbook/authentication?q= Example of how to integrate GitHub OAuth for user authentication in a Flet application. It demonstrates configuring the GitHub OAuth provider, initiating the login flow, and handling the login event to access user information and tokens. ```APIDOC ## Sign in with GitHub OAuth Provider ### Description This example demonstrates how to implement user authentication in a Flet application using GitHub as the OAuth 2.0 provider. It covers the necessary setup, including obtaining GitHub Client ID and Client Secret, configuring the `GitHubOAuthProvider`, initiating the login process via a button click, and handling the `on_login` event to retrieve user details and access tokens. ### Method `page.login(provider)` ### Endpoint `/oauth_callback` (handled internally by Flet) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import os import flet as ft from flet.auth.providers import GitHubOAuthProvider GITHUB_CLIENT_ID = os.getenv("GITHUB_CLIENT_ID") assert GITHUB_CLIENT_ID, "set GITHUB_CLIENT_ID environment variable" GITHUB_CLIENT_SECRET = os.getenv("GITHUB_CLIENT_SECRET") assert GITHUB_CLIENT_SECRET, "set GITHUB_CLIENT_SECRET environment variable" def main(page: ft.Page): provider = GitHubOAuthProvider( client_id=GITHUB_CLIENT_ID, client_secret=GITHUB_CLIENT_SECRET, redirect_url="http://localhost:8550/oauth_callback", ) def login_click(e): page.login(provider) def on_login(e): print("Login error:", e.error) print("Access token:", page.auth.token.access_token) print("User ID:", page.auth.user.id) page.on_login = on_login page.add(ft.Button("Login with GitHub", on_click=login_click)) ft.run(main, port=8550, view=ft.WEB_BROWSER) ``` ### Response #### Success Response (200) Upon successful login, the `page.on_login` event handler is called. The user details and authentication token are available via `page.auth.user` and `page.auth.token` respectively. - **page.auth.token.access_token** (string) - The access token obtained from the OAuth provider. - **page.auth.user.id** (string) - The unique identifier of the logged-in user. #### Response Example ```json { "Login error": null, "Access token": "gho_...", "User ID": "12345678" } ``` ### Error Handling - **Login Error**: If an error occurs during the login process, `e.error` in the `on_login` handler will contain the error message. ### Notes - Ensure that the `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` environment variables are set before running the application. - The `redirect_url` must match the one configured in your GitHub OAuth application settings. - For security, avoid embedding secrets directly in your source code. ``` -------------------------------- ### Stretching a TextField with expand Source: https://docs.flet.dev/cookbook/expanding-controls This example demonstrates how to use the expand property set to True on a TextField to make it fill all remaining horizontal space in a Row, while keeping the adjacent Button at its default size. ```python import flet as ft def main(page: ft.Page): page.add( ft.Container( width=480, padding=10, border=ft.Border.all(2, ft.Colors.BLUE_GREY_200), border_radius=10, content=ft.Row( controls=[ ft.TextField(hint_text="Enter your name", expand=True), ft.Button("Join chat"), ] ), ) ) if __name__ == "__main__": ft.run(main) ``` -------------------------------- ### Apply Opacity to Colors using with_opacity (Python) Source: https://docs.flet.dev/cookbook/colors This example demonstrates using the `with_opacity` method from Flet's color enums to apply transparency to a color. It returns a string representation of the color with opacity. ```python >>> ft.Colors.with_opacity(0.5, ft.Colors.RED) "red,0.5" >>> ft.CupertinoColors.with_opacity(0.8, ft.CupertinoColors.LINK) "link,0.8" ``` -------------------------------- ### Implement Composite Custom Controls Source: https://docs.flet.dev/cookbook/custom-controls Shows how to build a complex UI component by inheriting from a container control like Row. This example includes internal state management and event handling for editing and saving tasks. ```python import flet as ft @ft.control class Task(ft.Row): text: str = "" def init(self): self.text_view = ft.Text(value=self.text) self.text_edit = ft.TextField(value=self.text, visible=False) self.edit_button = ft.IconButton(icon=ft.Icons.EDIT, on_click=self.edit) self.save_button = ft.IconButton( visible=False, icon=ft.Icons.SAVE, on_click=self.save ) self.controls = [ ft.Checkbox(), self.text_view, self.text_edit, self.edit_button, self.save_button, ] def edit(self, e): self.edit_button.visible = False self.save_button.visible = True self.text_view.visible = False self.text_edit.visible = True self.update() def save(self, e): self.edit_button.visible = True self.save_button.visible = False self.text_view.visible = True self.text_edit.visible = False self.text_view.value = self.text_edit.value self.update() ``` -------------------------------- ### Implement Declarative CRUD with Flet Components Source: https://docs.flet.dev/cookbook/declarative-vs-imperative-crud-app?q= This example defines observable data models for Users and an App container, and uses functional components with hooks to manage transient UI state. It demonstrates how to separate durable data from local editing state while maintaining a reactive UI. ```python from dataclasses import dataclass, field import flet as ft @ft.observable @dataclass class User: first_name: str last_name: str def update(self, first_name: str, last_name: str): self.first_name = first_name self.last_name = last_name @ft.observable @dataclass class App: users: list[User] = field(default_factory=list) def add_user(self, first_name: str, last_name: str): if first_name.strip() or last_name.strip(): self.users.append(User(first_name, last_name)) def delete_user(self, user: User): self.users.remove(user) @ft.component def UserView(user: User, delete_user) -> ft.Control: # Local (transient) editing state—NOT in User is_editing, set_is_editing = ft.use_state(False) new_first_name, set_new_first_name = ft.use_state(user.first_name) new_last_name, set_new_last_name = ft.use_state(user.last_name) def start_edit(): set_new_first_name(user.first_name) set_new_last_name(user.last_name) set_is_editing(True) def save(): user.update(new_first_name, new_last_name) set_is_editing(False) def cancel(): set_is_editing(False) if not is_editing: return ft.Row( [ ft.Text(f"{user.first_name} {user.last_name}"), ft.Button("Edit", on_click=start_edit), ft.Button("Delete", on_click=lambda: delete_user(user)), ] ) return ft.Row( [ ft.TextField( label="First Name", value=new_first_name, on_change=lambda e: set_new_first_name(e.control.value), width=180, ), ft.TextField( label="Last Name", value=new_last_name, on_change=lambda e: set_new_last_name(e.control.value), width=180, ), ft.Button("Save", on_click=save), ft.Button("Cancel", on_click=cancel), ] ) @ft.component def AddUserForm(add_user) -> ft.Control: # Uses local buffers; calls parent action on Add new_first_name, set_new_first_name = ft.use_state("") new_last_name, set_new_last_name = ft.use_state("") def add_user_and_clear(): add_user(new_first_name, new_last_name) set_new_first_name("") set_new_last_name("") return ft.Row( controls=[ ft.TextField( label="First Name", width=200, value=new_first_name, on_change=lambda e: set_new_first_name(e.control.value), ), ft.TextField( label="Last Name", width=200, value=new_last_name, on_change=lambda e: set_new_last_name(e.control.value), ), ft.Button("Add", on_click=add_user_and_clear), ] ) @ft.component def AppView() -> list[ft.Control]: app, _ = ft.use_state( App( users=[ User("John", "Doe"), User("Jane", "Doe"), User("Foo", "Bar"), ] ) ) return [ AddUserForm(app.add_user), *[UserView(user, app.delete_user) for user in app.users], ] ft.run(lambda page: page.render(AppView)) ``` -------------------------------- ### Create Adaptive Flet App Source: https://docs.flet.dev/cookbook/adaptive-apps?q= This example shows a basic Flet application with `page.adaptive = True` enabled, resulting in a different UI appearance on iOS and Android platforms. It includes adaptive app bars, navigation bars, and various form controls. ```python import flet as ft def main(page): page.adaptive = True page.appbar = ft.AppBar( leading=ft.TextButton("New", style=ft.ButtonStyle(padding=0)), title=ft.Text("Adaptive AppBar"), actions=[ ft.IconButton(ft.cupertino_icons.ADD, style=ft.ButtonStyle(padding=0)) ], bgcolor=ft.Colors.with_opacity(0.04, ft.CupertinoColors.SYSTEM_BACKGROUND), ) page.navigation_bar = ft.NavigationBar( destinations=[ ft.NavigationBarDestination(icon=ft.Icons.EXPLORE, label="Explore"), ft.NavigationBarDestination(icon=ft.Icons.COMMUTE, label="Commute"), ft.NavigationBarDestination( icon=ft.Icons.BOOKMARK_BORDER, selected_icon=ft.Icons.BOOKMARK, label="Bookmark", ), ], border=ft.Border( top=ft.BorderSide(color=ft.CupertinoColors.SYSTEM_GREY2, width=0) ), ) page.add( ft.SafeArea( ft.Column( [ ft.Checkbox(value=False, label="Dark Mode"), ft.Text("First field:"), ft.TextField(keyboard_type=ft.KeyboardType.TEXT), ft.Text("Second field:"), ft.TextField(keyboard_type=ft.KeyboardType.TEXT), ft.Switch(label="A switch"), ft.FilledButton(content=ft.Text("Adaptive button")), ft.Text("Text line 1"), ft.Text("Text line 2"), ft.Text("Text line 3"), ] ) ) ) ft.run(main) ``` -------------------------------- ### Basic Flet App with Direct Control References Source: https://docs.flet.dev/cookbook/control-refs?q= This example demonstrates a simple Flet application where UI controls like TextFields and a Column are directly referenced using variables. These references are used to manipulate control properties and update the UI in response to user interactions, such as button clicks. ```python import flet as ft def main(page): first_name = ft.TextField(label="First name", autofocus=True) last_name = ft.TextField(label="Last name") greetings = ft.Column() async def btn_click(e): greetings.controls.append(ft.Text(f"Hello, {first_name.value} {last_name.value}!")) first_name.value = "" last_name.value = "" page.update() await first_name.focus() page.add( first_name, last_name, ft.Button("Say hello!", on_click=btn_click), greetings, ) ft.run(main) ``` -------------------------------- ### Sign Out and Clear Auth Token (Python) Source: https://docs.flet.dev/cookbook/authentication?q= Provides a Python example for handling user sign-out in a Flet application. It demonstrates removing the saved authentication token from client storage and then calling `page.logout()` to reset the authentication state and trigger the `on_logout` event. ```Python AUTH_TOKEN_KEY = "myapp.auth_token" # Example key async def logout_button_click(e): # Remove the saved token from client storage await page.shared_preferences.remove(AUTH_TOKEN_KEY) # Log out the user and reset auth state page.logout() ``` -------------------------------- ### Programmatic Navigation with Parameters Source: https://docs.flet.dev/cookbook/navigation-and-routing?q= Demonstrates how to navigate to a new route programmatically while passing optional query parameters. ```python await page.push_route("/search", q="flet", page=2) ``` -------------------------------- ### Client Storage Operations Source: https://docs.flet.dev/cookbook/client-storage?q= Methods to interact with the Flet client storage, including setting, getting, checking, and removing values. ```APIDOC ## Client Storage API ### Description Provides persistent key-value storage on the client device. Note that storage is shared across Flet apps; use prefixes to avoid collisions. ### Methods - **set(key, value)**: Stores a value. Supports strings, numbers, booleans, and lists. - **get(key)**: Retrieves a value, automatically converted to the original type. - **contains_key(key)**: Returns True if the key exists. - **get_keys(prefix)**: Retrieves all keys matching a specific prefix. - **remove(key)**: Removes a specific key-value pair. - **clear()**: Clears all preferences for the current user across all Flet apps. ### Request Example (Set) await page.shared_preferences.set("user.theme", "dark") ### Response Example (Get) value = await page.shared_preferences.get("user.theme") # Returns: "dark" ``` -------------------------------- ### Rotation Animation Source: https://docs.flet.dev/cookbook/animations?q= This section is intended to describe how to implement rotation animations using the `animate_rotation` property, but no code example is provided in the source text. ```APIDOC ## Rotation Animation Setting control's `animate_rotation` to either `True`, number or an instance of `Animation` class (see above) enables implicit animation of `LayoutControl.rotate` property. ### Request Example ```python # No code example provided in the source text. ``` ``` -------------------------------- ### Run Flet App on Fixed Port Source: https://docs.flet.dev/cookbook/authentication?q= Example of running a Flet application on a specific port, which is required for consistent OAuth redirect URL handling. ```python ft.run(main, port=8550) ``` -------------------------------- ### Accessing Initial Route in Flet Source: https://docs.flet.dev/cookbook/navigation-and-routing?q= Demonstrates how to retrieve and display the initial route of a Flet application upon startup. ```python import flet as ft def main(page: ft.Page): page.add(ft.Text(f"Initial route: {page.route}")) if __name__ == "__main__": ft.run(main) ``` -------------------------------- ### Set Control Background Color Directly (Python) Source: https://docs.flet.dev/cookbook/colors This example shows how to directly set the background color of a Flet control, such as a Card, using a predefined color value. ```python >>> ft.Card(bgcolor=ft.Colors.GREEN_200) ``` -------------------------------- ### Configure Application Theme and Color Schemes Source: https://docs.flet.dev/cookbook/colors?q= Shows how to set a global theme seed color or override specific color scheme values for consistent application styling. ```python page.theme = ft.Theme(color_scheme_seed=ft.Colors.GREEN) page.theme = ft.Theme( color_scheme=ft.ColorScheme( primary=ft.Colors.GREEN, error=ft.Colors.RED, ), ) ``` -------------------------------- ### Offset Animation Source: https://docs.flet.dev/cookbook/animations?q= Illustrates offset animation using `animate_offset` to create sliding effects. The example shows a container moving from an off-screen position to its default position with a bounce effect. ```APIDOC ## Offset Animation Setting control's `animate_offset` to either `True`, number or an instance of `Animation` class (see above) enables implicit animation of `LayoutControl.offset` property. `offset` property is an instance of `Offset` class which specifies horizontal `x` and vertical `y` offset of a control scaled to control's size. For example, an offset `Offset(-0.25, 0)` will result in a horizontal translation of one quarter the width of the control. Offset animation is used for various sliding effects: ### Request Example ```python import flet as ft def main(page: ft.Page): def animate(e: ft.Event[ft.Button]): container.offset = ft.Offset(0, 0) container.update() page.add( container := ft.Container( width=150, height=150, bgcolor=ft.Colors.BLUE, border_radius=ft.BorderRadius.all(10), offset=ft.Offset(x=-1.1, y=0), animate_offset=ft.Animation( duration=600, curve=ft.AnimationCurve.BOUNCE_OUT, ), ), ft.Button("Reveal!", on_click=animate), ) ft.run(main) ``` ``` -------------------------------- ### Get All Keys from Flet Session Storage Source: https://docs.flet.dev/cookbook/session-storage Provides the method `get_keys` to retrieve a list of all keys currently stored in the Flet session. This can be useful for iterating over all stored session data. ```python page.session.store.get_keys() ``` -------------------------------- ### Correct Shell Execution Patterns Source: https://docs.flet.dev/cookbook/subprocess Illustrates the difference between using shell=False with a list of arguments versus shell=True with a single string. It emphasizes that shell=False is the preferred, safer method. ```python # Preferred: shell=False with list of arguments subprocess.run( ["am", "start", "-n", "com.android.settings/.Settings", "--user", "0"], shell=False ) # Alternative: shell=True with a single string subprocess.run( "am start -n com.android.settings/.Settings --user 0", shell=True ) ``` -------------------------------- ### Set Theme Color Scheme Seed (Python) Source: https://docs.flet.dev/cookbook/colors This example demonstrates how to set the theme's color scheme seed for a Flet page. This seed color influences the generated theme colors. ```python >>> page.theme = ft.Theme(color_scheme_seed=ft.Colors.GREEN) ``` -------------------------------- ### Read Data from Session Storage in Flet Source: https://docs.flet.dev/cookbook/session-storage Illustrates how to retrieve data from the Flet session store using the `get` method. The stored values are automatically converted back to their original data types. ```python # The value is automatically converted back to the original type value = page.session.store.get("key") colors = page.session.store.get("favorite_colors") # colors = ["red", "green", "blue"] ``` -------------------------------- ### Async Flet App Initialization Source: https://docs.flet.dev/cookbook/async-apps Demonstrates how to define an async main function for a Flet application. This allows direct use of asyncio APIs like asyncio.sleep within the app's lifecycle. The app is run using ft.run(). ```python import flet as ft import asyncio async def main(page: ft.Page): await asyncio.sleep(1) page.add(ft.Text("Hello, async world!")) ft.run(main) ``` -------------------------------- ### Implement Nested and Overridden Themes Source: https://docs.flet.dev/cookbook/theming Demonstrates how to apply specific themes to individual containers, including overriding color schemes and forcing a unique theme mode that ignores parent inheritance. ```python import flet as ft def main(page: ft.Page): page.theme = ft.Theme(color_scheme_seed=ft.Colors.YELLOW) page.add( ft.Container(content=ft.Button("Page theme button"), bgcolor=ft.Colors.SURFACE_CONTAINER_HIGHEST, padding=20, width=300), ft.Container(theme=ft.Theme(color_scheme=ft.ColorScheme(primary=ft.Colors.PINK)), content=ft.Button("Inherited theme button"), bgcolor=ft.Colors.SURFACE_CONTAINER_HIGHEST, padding=20, width=300), ft.Container(theme=ft.Theme(color_scheme_seed=ft.Colors.INDIGO), theme_mode=ft.ThemeMode.DARK, content=ft.Button("Unique theme button"), bgcolor=ft.Colors.SURFACE_CONTAINER_HIGHEST, padding=20, width=300) ) ft.run(main) ``` -------------------------------- ### Configure Flet Main Application Layout Source: https://docs.flet.dev/cookbook/read-and-write-files?q= Sets up the Flet page structure including an AppBar with log viewing capabilities and a floating action button to trigger counter increments. ```python def main(page: ft.Page): page.theme_mode = ft.ThemeMode.LIGHT counter = Counter() def show_logs(e: ft.ControlEvent): if FLET_APP_CONSOLE is not None: with open(FLET_APP_CONSOLE, "r") as f: dlg = ft.AlertDialog(title=ft.Text("App Logs"), content=ft.Text(f.read()), scrollable=True) page.open(dlg) page.floating_action_button = ft.FloatingActionButton( icon=ft.Icons.ADD, on_click=lambda e: counter.increment() ) page.add(ft.SafeArea(counter)) ```