or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdcharts-visualization.mdevents-interaction.mdindex.mdlayout-navigation.mdtheming-styling.mdui-controls.mdutilities-platform.md

advanced-features.mddocs/

0

# Advanced Features

1

2

This document covers Flet's advanced capabilities including 2D canvas graphics, interactive maps, media controls, system integration, authentication, and advertisement features.

3

4

## Import

5

6

```python

7

import flet as ft

8

```

9

10

## Canvas and 2D Graphics

11

12

### Canvas

13

14

```python { .api }

15

class Canvas(Control):

16

"""2D drawing canvas control."""

17

18

def __init__(

19

self,

20

shapes: List[Shape] = None,

21

width: float = None,

22

height: float = None,

23

resize_interval: int = None,

24

content: Control = None,

25

on_resize: callable = None,

26

**kwargs

27

)

28

```

29

30

**Parameters:**

31

- `shapes` (List[Shape], optional): List of shapes to draw on canvas

32

- `width` (float, optional): Canvas width

33

- `height` (float, optional): Canvas height

34

- `resize_interval` (int, optional): Resize event throttling interval

35

- `content` (Control, optional): Child control overlaid on canvas

36

- `on_resize` (callable, optional): Canvas resize event handler

37

38

**Example:**

39

```python

40

import flet.canvas as cv

41

42

canvas = ft.Canvas(

43

shapes=[

44

cv.Circle(

45

x=100, y=100, radius=50,

46

paint=ft.Paint(

47

color=ft.colors.BLUE,

48

style=ft.PaintingStyle.FILL

49

)

50

),

51

cv.Line(

52

x1=0, y1=0, x2=200, y2=200,

53

paint=ft.Paint(

54

color=ft.colors.RED,

55

stroke_width=5

56

)

57

)

58

],

59

width=300,

60

height=300

61

)

62

```

63

64

### Canvas Shapes

65

66

#### Circle

67

68

```python { .api }

69

class Circle(Shape):

70

"""Circle shape for canvas."""

71

72

def __init__(

73

self,

74

x: float,

75

y: float,

76

radius: float,

77

paint: Paint = None,

78

**kwargs

79

)

80

```

81

82

#### Rect

83

84

```python { .api }

85

class Rect(Shape):

86

"""Rectangle shape for canvas."""

87

88

def __init__(

89

self,

90

x: float,

91

y: float,

92

width: float,

93

height: float,

94

border_radius: float = None,

95

paint: Paint = None,

96

**kwargs

97

)

98

```

99

100

#### Line

101

102

```python { .api }

103

class Line(Shape):

104

"""Line shape for canvas."""

105

106

def __init__(

107

self,

108

x1: float,

109

y1: float,

110

x2: float,

111

y2: float,

112

paint: Paint = None,

113

**kwargs

114

)

115

```

116

117

#### Arc

118

119

```python { .api }

120

class Arc(Shape):

121

"""Arc shape for canvas."""

122

123

def __init__(

124

self,

125

x: float,

126

y: float,

127

width: float,

128

height: float,

129

start_angle: float,

130

sweep_angle: float,

131

use_center: bool = False,

132

paint: Paint = None,

133

**kwargs

134

)

135

```

136

137

#### Path

138

139

```python { .api }

140

class Path(Shape):

141

"""Custom path shape for canvas."""

142

143

def __init__(

144

self,

145

elements: List[PathElement] = None,

146

paint: Paint = None,

147

**kwargs

148

)

149

```

150

151

#### Text

152

153

```python { .api }

154

class Text(Shape):

155

"""Text shape for canvas."""

156

157

def __init__(

158

self,

159

x: float,

160

y: float,

161

text: str,

162

style: TextStyle = None,

163

**kwargs

164

)

165

```

166

167

### Canvas Paint

168

169

```python { .api }

170

class Paint(Control):

171

"""Paint configuration for canvas shapes."""

172

173

def __init__(

174

self,

175

anti_alias: bool = None,

176

color: str = None,

177

blend_mode: BlendMode = None,

178

style: PaintingStyle = None,

179

stroke_width: float = None,

180

stroke_cap: StrokeCap = None,

181

stroke_join: StrokeJoin = None,

182

shader: Gradient = None,

183

mask_filter: MaskFilter = None,

184

color_filter: ColorFilter = None,

185

image_filter: ImageFilter = None,

186

**kwargs

187

)

188

```

189

190

**Example:**

191

```python

192

# Gradient filled circle

193

gradient_paint = ft.Paint(

194

shader=ft.LinearGradient(

195

begin=ft.Offset(0, 0),

196

end=ft.Offset(100, 100),

197

colors=[ft.colors.RED, ft.colors.BLUE]

198

),

199

style=ft.PaintingStyle.FILL

200

)

201

202

canvas.shapes.append(

203

cv.Circle(x=150, y=150, radius=75, paint=gradient_paint)

204

)

205

```

206

207

## Interactive Maps

208

209

### Map

210

211

```python { .api }

212

class Map(Control):

213

"""Interactive map control."""

214

215

def __init__(

216

self,

217

configuration: MapConfiguration = None,

218

layers: List[MapLayer] = None,

219

initial_center: MapLatitudeLongitude = None,

220

initial_zoom: float = None,

221

initial_rotation: float = None,

222

interaction_configuration: MapInteractionConfiguration = None,

223

on_init: callable = None,

224

on_tap: callable = None,

225

on_secondary_tap: callable = None,

226

on_long_press: callable = None,

227

on_position_changed: callable = None,

228

on_event: callable = None,

229

**kwargs

230

)

231

```

232

233

**Parameters:**

234

- `configuration` (MapConfiguration, optional): Map configuration

235

- `layers` (List[MapLayer], optional): Map layers

236

- `initial_center` (MapLatitudeLongitude, optional): Initial map center

237

- `initial_zoom` (float, optional): Initial zoom level

238

- `on_tap` (callable, optional): Map tap event handler

239

- `on_position_changed` (callable, optional): Position change event handler

240

241

**Example:**

242

```python

243

import flet.map as map

244

245

# Create interactive map

246

ft.Map(

247

expand=True,

248

configuration=map.MapConfiguration(

249

initial_center=map.MapLatitudeLongitude(37.7749, -122.4194),

250

initial_zoom=13,

251

interaction_configuration=map.MapInteractionConfiguration(

252

flags=map.MapInteractiveFlag.ALL

253

)

254

),

255

layers=[

256

map.TileLayer(

257

url_template="https://tile.openstreetmap.org/{z}/{x}/{y}.png",

258

user_agent_package_name="com.example.app"

259

),

260

map.MarkerLayer(

261

markers=[

262

map.Marker(

263

content=ft.Icon(ft.icons.LOCATION_ON),

264

coordinates=map.MapLatitudeLongitude(37.7749, -122.4194)

265

)

266

]

267

)

268

]

269

)

270

```

271

272

### Map Layers

273

274

#### TileLayer

275

276

```python { .api }

277

class TileLayer(MapLayer):

278

"""Map tile layer."""

279

280

def __init__(

281

self,

282

url_template: str,

283

user_agent_package_name: str = None,

284

fallback_url: str = None,

285

additional_options: dict = None,

286

background_color: str = None,

287

error_tile_path: str = None,

288

max_zoom: float = None,

289

min_zoom: float = None,

290

tile_size: int = None,

291

**kwargs

292

)

293

```

294

295

#### MarkerLayer

296

297

```python { .api }

298

class MarkerLayer(MapLayer):

299

"""Map marker layer."""

300

301

def __init__(

302

self,

303

markers: List[Marker] = None,

304

**kwargs

305

)

306

```

307

308

#### CircleLayer

309

310

```python { .api }

311

class CircleLayer(MapLayer):

312

"""Circle overlay layer."""

313

314

def __init__(

315

self,

316

circles: List[CircleMarker] = None,

317

**kwargs

318

)

319

```

320

321

#### PolygonLayer

322

323

```python { .api }

324

class PolygonLayer(MapLayer):

325

"""Polygon overlay layer."""

326

327

def __init__(

328

self,

329

polygons: List[PolygonMarker] = None,

330

**kwargs

331

)

332

```

333

334

#### PolylineLayer

335

336

```python { .api }

337

class PolylineLayer(MapLayer):

338

"""Polyline overlay layer."""

339

340

def __init__(

341

self,

342

polylines: List[PolylineMarker] = None,

343

**kwargs

344

)

345

```

346

347

### Map Markers

348

349

#### Marker

350

351

```python { .api }

352

class Marker(Control):

353

"""Map marker."""

354

355

def __init__(

356

self,

357

content: Control = None,

358

coordinates: MapLatitudeLongitude = None,

359

width: float = None,

360

height: float = None,

361

alignment: Alignment = None,

362

rotate: bool = None,

363

**kwargs

364

)

365

```

366

367

#### CircleMarker

368

369

```python { .api }

370

class CircleMarker(Control):

371

"""Circle marker on map."""

372

373

def __init__(

374

self,

375

coordinates: MapLatitudeLongitude = None,

376

radius: float = None,

377

color: str = None,

378

border_color: str = None,

379

border_stroke_width: float = None,

380

use_radius_in_meter: bool = None,

381

**kwargs

382

)

383

```

384

385

## Media Controls

386

387

### Audio

388

389

```python { .api }

390

class Audio(Control):

391

"""Audio player control."""

392

393

def __init__(

394

self,

395

src: str = None,

396

src_base64: str = None,

397

autoplay: bool = None,

398

volume: float = None,

399

balance: float = None,

400

playback_rate: float = None,

401

on_position_changed: callable = None,

402

on_duration_changed: callable = None,

403

on_state_changed: callable = None,

404

on_seek_complete: callable = None,

405

**kwargs

406

)

407

408

def play(self) -> None:

409

"""Start audio playback."""

410

411

def pause(self) -> None:

412

"""Pause audio playback."""

413

414

def stop(self) -> None:

415

"""Stop audio playback."""

416

417

def seek(self, position_milliseconds: int) -> None:

418

"""Seek to specific position."""

419

```

420

421

**Parameters:**

422

- `src` (str, optional): Audio file URL or path

423

- `src_base64` (str, optional): Base64-encoded audio data

424

- `autoplay` (bool, optional): Start playing automatically

425

- `volume` (float, optional): Volume level (0.0-1.0)

426

- `playback_rate` (float, optional): Playback speed

427

- `on_state_changed` (callable, optional): Playback state change event

428

429

**Example:**

430

```python

431

def on_state_changed(e):

432

print(f"Audio state: {e.data}")

433

434

audio = ft.Audio(

435

src="https://example.com/audio.mp3",

436

autoplay=False,

437

volume=0.5,

438

on_state_changed=on_state_changed

439

)

440

441

# Control buttons

442

ft.Row([

443

ft.IconButton(ft.icons.PLAY_ARROW, on_click=lambda _: audio.play()),

444

ft.IconButton(ft.icons.PAUSE, on_click=lambda _: audio.pause()),

445

ft.IconButton(ft.icons.STOP, on_click=lambda _: audio.stop())

446

])

447

```

448

449

### AudioRecorder

450

451

```python { .api }

452

class AudioRecorder(Control):

453

"""Audio recording control."""

454

455

def __init__(

456

self,

457

audio_encoder: AudioEncoder = None,

458

bit_rate: int = None,

459

sampling_rate: int = None,

460

on_state_changed: callable = None,

461

**kwargs

462

)

463

464

def start_recording(self, output_path: str) -> None:

465

"""Start recording to file."""

466

467

def stop_recording(self) -> None:

468

"""Stop recording."""

469

470

def has_permission(self) -> bool:

471

"""Check if recording permission is granted."""

472

```

473

474

### Video

475

476

```python { .api }

477

class Video(Control):

478

"""Video player control."""

479

480

def __init__(

481

self,

482

playlist: List[VideoMedia] = None,

483

playlist_mode: PlaylistMode = None,

484

fill_color: str = None,

485

aspect_ratio: float = None,

486

volume: float = None,

487

balance: float = None,

488

playback_rate: float = None,

489

filter_quality: FilterQuality = None,

490

wakelock: bool = None,

491

autoplay: bool = None,

492

show_controls: bool = True,

493

subtitle_configuration: VideoSubtitleConfiguration = None,

494

configuration: VideoConfiguration = None,

495

on_position_changed: callable = None,

496

on_duration_changed: callable = None,

497

on_seek_complete: callable = None,

498

**kwargs

499

)

500

501

def play(self) -> None:

502

"""Start video playback."""

503

504

def pause(self) -> None:

505

"""Pause video playback."""

506

507

def stop(self) -> None:

508

"""Stop video playback."""

509

510

def seek(self, position_milliseconds: int) -> None:

511

"""Seek to specific position."""

512

```

513

514

### WebView

515

516

```python { .api }

517

class WebView(Control):

518

"""Web view control for displaying web content."""

519

520

def __init__(

521

self,

522

url: str = None,

523

html: str = None,

524

javascript_enabled: bool = True,

525

background_color: str = None,

526

prevent_link: bool = None,

527

on_page_started: callable = None,

528

on_page_ended: callable = None,

529

on_web_resource_error: callable = None,

530

on_url_change: callable = None,

531

**kwargs

532

)

533

534

def load_url(self, url: str) -> None:

535

"""Load URL in web view."""

536

537

def load_html(self, html: str) -> None:

538

"""Load HTML content."""

539

540

def evaluate_javascript(self, script: str) -> None:

541

"""Execute JavaScript code."""

542

```

543

544

**Example:**

545

```python

546

webview = ft.WebView(

547

url="https://flet.dev",

548

javascript_enabled=True,

549

on_page_ended=lambda e: print(f"Page loaded: {e.data}"),

550

expand=True

551

)

552

```

553

554

## System Integration

555

556

### Geolocator

557

558

```python { .api }

559

class Geolocator(Control):

560

"""GPS location services."""

561

562

def __init__(

563

self,

564

on_position_changed: callable = None,

565

on_error: callable = None,

566

**kwargs

567

)

568

569

def request_permission(self) -> None:

570

"""Request location permission."""

571

572

def get_current_position(self) -> None:

573

"""Get current GPS position."""

574

575

def get_location_accuracy(self) -> None:

576

"""Get location accuracy."""

577

578

def is_location_service_enabled(self) -> None:

579

"""Check if location services are enabled."""

580

```

581

582

**Example:**

583

```python

584

def on_position_changed(e):

585

print(f"Position: {e.latitude}, {e.longitude}")

586

587

geolocator = ft.Geolocator(

588

on_position_changed=on_position_changed

589

)

590

591

ft.ElevatedButton(

592

"Get Location",

593

on_click=lambda _: geolocator.get_current_position()

594

)

595

```

596

597

### PermissionHandler

598

599

```python { .api }

600

class PermissionHandler(Control):

601

"""System permissions management."""

602

603

def __init__(

604

self,

605

on_result: callable = None,

606

**kwargs

607

)

608

609

def request_permission(self, permission: Permission) -> None:

610

"""Request specific permission."""

611

612

def check_permission(self, permission: Permission) -> None:

613

"""Check permission status."""

614

615

def open_app_settings(self) -> None:

616

"""Open app settings."""

617

```

618

619

### HapticFeedback

620

621

```python { .api }

622

class HapticFeedback(Control):

623

"""Device haptic feedback control."""

624

625

def heavy_impact(self) -> None:

626

"""Heavy impact haptic feedback."""

627

628

def medium_impact(self) -> None:

629

"""Medium impact haptic feedback."""

630

631

def light_impact(self) -> None:

632

"""Light impact haptic feedback."""

633

634

def vibrate(self, pattern: List[int] = None) -> None:

635

"""Custom vibration pattern."""

636

```

637

638

### Flashlight

639

640

```python { .api }

641

class Flashlight(Control):

642

"""Device flashlight control."""

643

644

def __init__(

645

self,

646

on_result: callable = None,

647

**kwargs

648

)

649

650

def turn_on(self) -> None:

651

"""Turn on flashlight."""

652

653

def turn_off(self) -> None:

654

"""Turn off flashlight."""

655

656

def is_available(self) -> None:

657

"""Check if flashlight is available."""

658

```

659

660

### ShakeDetector

661

662

```python { .api }

663

class ShakeDetector(Control):

664

"""Device shake detection."""

665

666

def __init__(

667

self,

668

minimum_shake_count: int = None,

669

shake_slop_time_ms: int = None,

670

shake_count_reset_time_ms: int = None,

671

on_shake: callable = None,

672

**kwargs

673

)

674

675

def start_listening(self) -> None:

676

"""Start shake detection."""

677

678

def stop_listening(self) -> None:

679

"""Stop shake detection."""

680

```

681

682

## Authentication

683

684

### Authorization

685

686

```python { .api }

687

class Authorization(Control):

688

"""OAuth authorization handler."""

689

690

def __init__(

691

self,

692

provider: OAuthProvider = None,

693

on_result: callable = None,

694

**kwargs

695

)

696

```

697

698

### OAuthProvider

699

700

```python { .api }

701

class OAuthProvider(Control):

702

"""OAuth provider configuration."""

703

704

def __init__(

705

self,

706

client_id: str = None,

707

client_secret: str = None,

708

authorization_endpoint: str = None,

709

token_endpoint: str = None,

710

redirect_url: str = None,

711

scope: List[str] = None,

712

**kwargs

713

)

714

```

715

716

### User

717

718

```python { .api }

719

class User(Control):

720

"""User information."""

721

722

def __init__(

723

self,

724

uid: str = None,

725

email: str = None,

726

display_name: str = None,

727

photo_url: str = None,

728

phone_number: str = None,

729

provider_id: str = None,

730

**kwargs

731

)

732

```

733

734

**Example:**

735

```python

736

# OAuth configuration

737

oauth_provider = ft.OAuthProvider(

738

client_id="your_client_id",

739

client_secret="your_client_secret",

740

authorization_endpoint="https://oauth.provider.com/auth",

741

token_endpoint="https://oauth.provider.com/token",

742

redirect_url="https://yourapp.com/callback",

743

scope=["read", "write"]

744

)

745

746

def handle_auth_result(e):

747

if e.data == "success":

748

print("Authentication successful")

749

else:

750

print(f"Authentication failed: {e.error}")

751

752

auth = ft.Authorization(

753

provider=oauth_provider,

754

on_result=handle_auth_result

755

)

756

```

757

758

## Advertisement Integration

759

760

### BannerAd

761

762

```python { .api }

763

class BannerAd(Control):

764

"""Banner advertisement control."""

765

766

def __init__(

767

self,

768

unit_id: str = None,

769

size: BannerAdSize = None,

770

on_click: callable = None,

771

on_impression: callable = None,

772

on_will_dismiss_screen: callable = None,

773

on_did_dismiss_screen: callable = None,

774

**kwargs

775

)

776

```

777

778

### InterstitialAd

779

780

```python { .api }

781

class InterstitialAd(Control):

782

"""Interstitial advertisement control."""

783

784

def __init__(

785

self,

786

unit_id: str = None,

787

on_loaded: callable = None,

788

on_failed_to_load: callable = None,

789

on_impression: callable = None,

790

on_clicked: callable = None,

791

on_will_dismiss_screen: callable = None,

792

on_did_dismiss_screen: callable = None,

793

**kwargs

794

)

795

796

def load(self) -> None:

797

"""Load interstitial ad."""

798

799

def show(self) -> None:

800

"""Show interstitial ad."""

801

```

802

803

**Example:**

804

```python

805

# Banner ad

806

banner = ft.BannerAd(

807

unit_id="ca-app-pub-1234567890123456/1234567890",

808

size=ft.BannerAdSize.BANNER,

809

on_click=lambda e: print("Banner clicked"),

810

on_impression=lambda e: print("Banner impression")

811

)

812

813

# Interstitial ad

814

def show_interstitial(e):

815

interstitial.load()

816

817

def on_interstitial_loaded(e):

818

interstitial.show()

819

820

interstitial = ft.InterstitialAd(

821

unit_id="ca-app-pub-1234567890123456/0987654321",

822

on_loaded=on_interstitial_loaded,

823

on_clicked=lambda e: print("Interstitial clicked")

824

)

825

826

ft.ElevatedButton("Show Ad", on_click=show_interstitial)

827

```

828

829

## Advanced Features Examples

830

831

### Real-time Canvas Drawing

832

833

```python

834

def create_drawing_app():

835

canvas_shapes = []

836

837

def on_pan_update(e):

838

canvas_shapes.append(

839

cv.Circle(

840

x=e.local_x, y=e.local_y, radius=5,

841

paint=ft.Paint(color=ft.colors.BLUE)

842

)

843

)

844

canvas.shapes = canvas_shapes.copy()

845

canvas.update()

846

847

canvas = ft.Canvas(

848

width=400, height=400,

849

shapes=canvas_shapes

850

)

851

852

return ft.GestureDetector(

853

content=canvas,

854

on_pan_update=on_pan_update

855

)

856

```

857

858

### Interactive Map with Custom Markers

859

860

```python

861

def create_map_with_markers():

862

markers = []

863

864

def add_marker(lat, lng, title):

865

marker = map.Marker(

866

content=ft.Container(

867

content=ft.Column([

868

ft.Icon(ft.icons.LOCATION_ON, color=ft.colors.RED),

869

ft.Text(title, size=12)

870

], tight=True),

871

bgcolor=ft.colors.WHITE,

872

padding=5,

873

border_radius=5

874

),

875

coordinates=map.MapLatitudeLongitude(lat, lng)

876

)

877

markers.append(marker)

878

return marker

879

880

# Add sample markers

881

add_marker(37.7749, -122.4194, "San Francisco")

882

add_marker(40.7128, -74.0060, "New York")

883

884

return ft.Map(

885

expand=True,

886

configuration=map.MapConfiguration(

887

initial_center=map.MapLatitudeLongitude(39.8283, -98.5795),

888

initial_zoom=4

889

),

890

layers=[

891

map.TileLayer(

892

url_template="https://tile.openstreetmap.org/{z}/{x}/{y}.png",

893

user_agent_package_name="com.example.app"

894

),

895

map.MarkerLayer(markers=markers)

896

]

897

)

898

```

899

900

### Media Player with Controls

901

902

```python

903

def create_media_player():

904

audio = ft.Audio(src="https://example.com/audio.mp3")

905

906

def on_state_changed(e):

907

if e.data == "playing":

908

play_button.icon = ft.icons.PAUSE

909

else:

910

play_button.icon = ft.icons.PLAY_ARROW

911

page.update()

912

913

def toggle_playback(e):

914

if audio.get_current_position() > 0:

915

audio.pause()

916

else:

917

audio.play()

918

919

play_button = ft.IconButton(

920

icon=ft.icons.PLAY_ARROW,

921

on_click=toggle_playback

922

)

923

924

audio.on_state_changed = on_state_changed

925

926

return ft.Column([

927

audio,

928

ft.Row([

929

play_button,

930

ft.IconButton(ft.icons.STOP, on_click=lambda _: audio.stop()),

931

ft.Slider(min=0, max=100, value=50, label="Volume")

932

])

933

])

934

```

935

936

This covers Flet's advanced features, enabling you to create sophisticated applications with graphics, maps, media, system integration, authentication, and monetization capabilities.