Flet is a rich User Interface framework to quickly build interactive web, desktop and mobile apps in Python without prior knowledge of web technologies.
—
This document covers Flet's advanced capabilities including 2D canvas graphics, interactive maps, media controls, system integration, authentication, and advertisement features.
import flet as ftclass Canvas(Control):
"""2D drawing canvas control."""
def __init__(
self,
shapes: List[Shape] = None,
width: float = None,
height: float = None,
resize_interval: int = None,
content: Control = None,
on_resize: callable = None,
**kwargs
)Parameters:
shapes (List[Shape], optional): List of shapes to draw on canvaswidth (float, optional): Canvas widthheight (float, optional): Canvas heightresize_interval (int, optional): Resize event throttling intervalcontent (Control, optional): Child control overlaid on canvason_resize (callable, optional): Canvas resize event handlerExample:
import flet.canvas as cv
canvas = ft.Canvas(
shapes=[
cv.Circle(
x=100, y=100, radius=50,
paint=ft.Paint(
color=ft.colors.BLUE,
style=ft.PaintingStyle.FILL
)
),
cv.Line(
x1=0, y1=0, x2=200, y2=200,
paint=ft.Paint(
color=ft.colors.RED,
stroke_width=5
)
)
],
width=300,
height=300
)class Circle(Shape):
"""Circle shape for canvas."""
def __init__(
self,
x: float,
y: float,
radius: float,
paint: Paint = None,
**kwargs
)class Rect(Shape):
"""Rectangle shape for canvas."""
def __init__(
self,
x: float,
y: float,
width: float,
height: float,
border_radius: float = None,
paint: Paint = None,
**kwargs
)class Line(Shape):
"""Line shape for canvas."""
def __init__(
self,
x1: float,
y1: float,
x2: float,
y2: float,
paint: Paint = None,
**kwargs
)class Arc(Shape):
"""Arc shape for canvas."""
def __init__(
self,
x: float,
y: float,
width: float,
height: float,
start_angle: float,
sweep_angle: float,
use_center: bool = False,
paint: Paint = None,
**kwargs
)class Path(Shape):
"""Custom path shape for canvas."""
def __init__(
self,
elements: List[PathElement] = None,
paint: Paint = None,
**kwargs
)class Text(Shape):
"""Text shape for canvas."""
def __init__(
self,
x: float,
y: float,
text: str,
style: TextStyle = None,
**kwargs
)class Paint(Control):
"""Paint configuration for canvas shapes."""
def __init__(
self,
anti_alias: bool = None,
color: str = None,
blend_mode: BlendMode = None,
style: PaintingStyle = None,
stroke_width: float = None,
stroke_cap: StrokeCap = None,
stroke_join: StrokeJoin = None,
shader: Gradient = None,
mask_filter: MaskFilter = None,
color_filter: ColorFilter = None,
image_filter: ImageFilter = None,
**kwargs
)Example:
# Gradient filled circle
gradient_paint = ft.Paint(
shader=ft.LinearGradient(
begin=ft.Offset(0, 0),
end=ft.Offset(100, 100),
colors=[ft.colors.RED, ft.colors.BLUE]
),
style=ft.PaintingStyle.FILL
)
canvas.shapes.append(
cv.Circle(x=150, y=150, radius=75, paint=gradient_paint)
)class Map(Control):
"""Interactive map control."""
def __init__(
self,
configuration: MapConfiguration = None,
layers: List[MapLayer] = None,
initial_center: MapLatitudeLongitude = None,
initial_zoom: float = None,
initial_rotation: float = None,
interaction_configuration: MapInteractionConfiguration = None,
on_init: callable = None,
on_tap: callable = None,
on_secondary_tap: callable = None,
on_long_press: callable = None,
on_position_changed: callable = None,
on_event: callable = None,
**kwargs
)Parameters:
configuration (MapConfiguration, optional): Map configurationlayers (List[MapLayer], optional): Map layersinitial_center (MapLatitudeLongitude, optional): Initial map centerinitial_zoom (float, optional): Initial zoom levelon_tap (callable, optional): Map tap event handleron_position_changed (callable, optional): Position change event handlerExample:
import flet.map as map
# Create interactive map
ft.Map(
expand=True,
configuration=map.MapConfiguration(
initial_center=map.MapLatitudeLongitude(37.7749, -122.4194),
initial_zoom=13,
interaction_configuration=map.MapInteractionConfiguration(
flags=map.MapInteractiveFlag.ALL
)
),
layers=[
map.TileLayer(
url_template="https://tile.openstreetmap.org/{z}/{x}/{y}.png",
user_agent_package_name="com.example.app"
),
map.MarkerLayer(
markers=[
map.Marker(
content=ft.Icon(ft.icons.LOCATION_ON),
coordinates=map.MapLatitudeLongitude(37.7749, -122.4194)
)
]
)
]
)class TileLayer(MapLayer):
"""Map tile layer."""
def __init__(
self,
url_template: str,
user_agent_package_name: str = None,
fallback_url: str = None,
additional_options: dict = None,
background_color: str = None,
error_tile_path: str = None,
max_zoom: float = None,
min_zoom: float = None,
tile_size: int = None,
**kwargs
)class MarkerLayer(MapLayer):
"""Map marker layer."""
def __init__(
self,
markers: List[Marker] = None,
**kwargs
)class CircleLayer(MapLayer):
"""Circle overlay layer."""
def __init__(
self,
circles: List[CircleMarker] = None,
**kwargs
)class PolygonLayer(MapLayer):
"""Polygon overlay layer."""
def __init__(
self,
polygons: List[PolygonMarker] = None,
**kwargs
)class PolylineLayer(MapLayer):
"""Polyline overlay layer."""
def __init__(
self,
polylines: List[PolylineMarker] = None,
**kwargs
)class Marker(Control):
"""Map marker."""
def __init__(
self,
content: Control = None,
coordinates: MapLatitudeLongitude = None,
width: float = None,
height: float = None,
alignment: Alignment = None,
rotate: bool = None,
**kwargs
)class CircleMarker(Control):
"""Circle marker on map."""
def __init__(
self,
coordinates: MapLatitudeLongitude = None,
radius: float = None,
color: str = None,
border_color: str = None,
border_stroke_width: float = None,
use_radius_in_meter: bool = None,
**kwargs
)class Audio(Control):
"""Audio player control."""
def __init__(
self,
src: str = None,
src_base64: str = None,
autoplay: bool = None,
volume: float = None,
balance: float = None,
playback_rate: float = None,
on_position_changed: callable = None,
on_duration_changed: callable = None,
on_state_changed: callable = None,
on_seek_complete: callable = None,
**kwargs
)
def play(self) -> None:
"""Start audio playback."""
def pause(self) -> None:
"""Pause audio playback."""
def stop(self) -> None:
"""Stop audio playback."""
def seek(self, position_milliseconds: int) -> None:
"""Seek to specific position."""Parameters:
src (str, optional): Audio file URL or pathsrc_base64 (str, optional): Base64-encoded audio dataautoplay (bool, optional): Start playing automaticallyvolume (float, optional): Volume level (0.0-1.0)playback_rate (float, optional): Playback speedon_state_changed (callable, optional): Playback state change eventExample:
def on_state_changed(e):
print(f"Audio state: {e.data}")
audio = ft.Audio(
src="https://example.com/audio.mp3",
autoplay=False,
volume=0.5,
on_state_changed=on_state_changed
)
# Control buttons
ft.Row([
ft.IconButton(ft.icons.PLAY_ARROW, on_click=lambda _: audio.play()),
ft.IconButton(ft.icons.PAUSE, on_click=lambda _: audio.pause()),
ft.IconButton(ft.icons.STOP, on_click=lambda _: audio.stop())
])class AudioRecorder(Control):
"""Audio recording control."""
def __init__(
self,
audio_encoder: AudioEncoder = None,
bit_rate: int = None,
sampling_rate: int = None,
on_state_changed: callable = None,
**kwargs
)
def start_recording(self, output_path: str) -> None:
"""Start recording to file."""
def stop_recording(self) -> None:
"""Stop recording."""
def has_permission(self) -> bool:
"""Check if recording permission is granted."""class Video(Control):
"""Video player control."""
def __init__(
self,
playlist: List[VideoMedia] = None,
playlist_mode: PlaylistMode = None,
fill_color: str = None,
aspect_ratio: float = None,
volume: float = None,
balance: float = None,
playback_rate: float = None,
filter_quality: FilterQuality = None,
wakelock: bool = None,
autoplay: bool = None,
show_controls: bool = True,
subtitle_configuration: VideoSubtitleConfiguration = None,
configuration: VideoConfiguration = None,
on_position_changed: callable = None,
on_duration_changed: callable = None,
on_seek_complete: callable = None,
**kwargs
)
def play(self) -> None:
"""Start video playback."""
def pause(self) -> None:
"""Pause video playback."""
def stop(self) -> None:
"""Stop video playback."""
def seek(self, position_milliseconds: int) -> None:
"""Seek to specific position."""class WebView(Control):
"""Web view control for displaying web content."""
def __init__(
self,
url: str = None,
html: str = None,
javascript_enabled: bool = True,
background_color: str = None,
prevent_link: bool = None,
on_page_started: callable = None,
on_page_ended: callable = None,
on_web_resource_error: callable = None,
on_url_change: callable = None,
**kwargs
)
def load_url(self, url: str) -> None:
"""Load URL in web view."""
def load_html(self, html: str) -> None:
"""Load HTML content."""
def evaluate_javascript(self, script: str) -> None:
"""Execute JavaScript code."""Example:
webview = ft.WebView(
url="https://flet.dev",
javascript_enabled=True,
on_page_ended=lambda e: print(f"Page loaded: {e.data}"),
expand=True
)class Geolocator(Control):
"""GPS location services."""
def __init__(
self,
on_position_changed: callable = None,
on_error: callable = None,
**kwargs
)
def request_permission(self) -> None:
"""Request location permission."""
def get_current_position(self) -> None:
"""Get current GPS position."""
def get_location_accuracy(self) -> None:
"""Get location accuracy."""
def is_location_service_enabled(self) -> None:
"""Check if location services are enabled."""Example:
def on_position_changed(e):
print(f"Position: {e.latitude}, {e.longitude}")
geolocator = ft.Geolocator(
on_position_changed=on_position_changed
)
ft.ElevatedButton(
"Get Location",
on_click=lambda _: geolocator.get_current_position()
)class PermissionHandler(Control):
"""System permissions management."""
def __init__(
self,
on_result: callable = None,
**kwargs
)
def request_permission(self, permission: Permission) -> None:
"""Request specific permission."""
def check_permission(self, permission: Permission) -> None:
"""Check permission status."""
def open_app_settings(self) -> None:
"""Open app settings."""class HapticFeedback(Control):
"""Device haptic feedback control."""
def heavy_impact(self) -> None:
"""Heavy impact haptic feedback."""
def medium_impact(self) -> None:
"""Medium impact haptic feedback."""
def light_impact(self) -> None:
"""Light impact haptic feedback."""
def vibrate(self, pattern: List[int] = None) -> None:
"""Custom vibration pattern."""class Flashlight(Control):
"""Device flashlight control."""
def __init__(
self,
on_result: callable = None,
**kwargs
)
def turn_on(self) -> None:
"""Turn on flashlight."""
def turn_off(self) -> None:
"""Turn off flashlight."""
def is_available(self) -> None:
"""Check if flashlight is available."""class ShakeDetector(Control):
"""Device shake detection."""
def __init__(
self,
minimum_shake_count: int = None,
shake_slop_time_ms: int = None,
shake_count_reset_time_ms: int = None,
on_shake: callable = None,
**kwargs
)
def start_listening(self) -> None:
"""Start shake detection."""
def stop_listening(self) -> None:
"""Stop shake detection."""class Authorization(Control):
"""OAuth authorization handler."""
def __init__(
self,
provider: OAuthProvider = None,
on_result: callable = None,
**kwargs
)class OAuthProvider(Control):
"""OAuth provider configuration."""
def __init__(
self,
client_id: str = None,
client_secret: str = None,
authorization_endpoint: str = None,
token_endpoint: str = None,
redirect_url: str = None,
scope: List[str] = None,
**kwargs
)class User(Control):
"""User information."""
def __init__(
self,
uid: str = None,
email: str = None,
display_name: str = None,
photo_url: str = None,
phone_number: str = None,
provider_id: str = None,
**kwargs
)Example:
# OAuth configuration
oauth_provider = ft.OAuthProvider(
client_id="your_client_id",
client_secret="your_client_secret",
authorization_endpoint="https://oauth.provider.com/auth",
token_endpoint="https://oauth.provider.com/token",
redirect_url="https://yourapp.com/callback",
scope=["read", "write"]
)
def handle_auth_result(e):
if e.data == "success":
print("Authentication successful")
else:
print(f"Authentication failed: {e.error}")
auth = ft.Authorization(
provider=oauth_provider,
on_result=handle_auth_result
)class BannerAd(Control):
"""Banner advertisement control."""
def __init__(
self,
unit_id: str = None,
size: BannerAdSize = None,
on_click: callable = None,
on_impression: callable = None,
on_will_dismiss_screen: callable = None,
on_did_dismiss_screen: callable = None,
**kwargs
)class InterstitialAd(Control):
"""Interstitial advertisement control."""
def __init__(
self,
unit_id: str = None,
on_loaded: callable = None,
on_failed_to_load: callable = None,
on_impression: callable = None,
on_clicked: callable = None,
on_will_dismiss_screen: callable = None,
on_did_dismiss_screen: callable = None,
**kwargs
)
def load(self) -> None:
"""Load interstitial ad."""
def show(self) -> None:
"""Show interstitial ad."""Example:
# Banner ad
banner = ft.BannerAd(
unit_id="ca-app-pub-1234567890123456/1234567890",
size=ft.BannerAdSize.BANNER,
on_click=lambda e: print("Banner clicked"),
on_impression=lambda e: print("Banner impression")
)
# Interstitial ad
def show_interstitial(e):
interstitial.load()
def on_interstitial_loaded(e):
interstitial.show()
interstitial = ft.InterstitialAd(
unit_id="ca-app-pub-1234567890123456/0987654321",
on_loaded=on_interstitial_loaded,
on_clicked=lambda e: print("Interstitial clicked")
)
ft.ElevatedButton("Show Ad", on_click=show_interstitial)def create_drawing_app():
canvas_shapes = []
def on_pan_update(e):
canvas_shapes.append(
cv.Circle(
x=e.local_x, y=e.local_y, radius=5,
paint=ft.Paint(color=ft.colors.BLUE)
)
)
canvas.shapes = canvas_shapes.copy()
canvas.update()
canvas = ft.Canvas(
width=400, height=400,
shapes=canvas_shapes
)
return ft.GestureDetector(
content=canvas,
on_pan_update=on_pan_update
)def create_map_with_markers():
markers = []
def add_marker(lat, lng, title):
marker = map.Marker(
content=ft.Container(
content=ft.Column([
ft.Icon(ft.icons.LOCATION_ON, color=ft.colors.RED),
ft.Text(title, size=12)
], tight=True),
bgcolor=ft.colors.WHITE,
padding=5,
border_radius=5
),
coordinates=map.MapLatitudeLongitude(lat, lng)
)
markers.append(marker)
return marker
# Add sample markers
add_marker(37.7749, -122.4194, "San Francisco")
add_marker(40.7128, -74.0060, "New York")
return ft.Map(
expand=True,
configuration=map.MapConfiguration(
initial_center=map.MapLatitudeLongitude(39.8283, -98.5795),
initial_zoom=4
),
layers=[
map.TileLayer(
url_template="https://tile.openstreetmap.org/{z}/{x}/{y}.png",
user_agent_package_name="com.example.app"
),
map.MarkerLayer(markers=markers)
]
)def create_media_player():
audio = ft.Audio(src="https://example.com/audio.mp3")
def on_state_changed(e):
if e.data == "playing":
play_button.icon = ft.icons.PAUSE
else:
play_button.icon = ft.icons.PLAY_ARROW
page.update()
def toggle_playback(e):
if audio.get_current_position() > 0:
audio.pause()
else:
audio.play()
play_button = ft.IconButton(
icon=ft.icons.PLAY_ARROW,
on_click=toggle_playback
)
audio.on_state_changed = on_state_changed
return ft.Column([
audio,
ft.Row([
play_button,
ft.IconButton(ft.icons.STOP, on_click=lambda _: audio.stop()),
ft.Slider(min=0, max=100, value=50, label="Volume")
])
])This covers Flet's advanced features, enabling you to create sophisticated applications with graphics, maps, media, system integration, authentication, and monetization capabilities.
Install with Tessl CLI
npx tessl i tessl/pypi-flet