Skip to main content

Canvas

ยท 3 min read
Feodor Fitsner
Flet founder and developer

Unleash your inner artist ๐Ÿง‘โ€๐ŸŽจ and boost your Flet creativity with brand-new Canvas control just released in Flet 0.6.0!

Canvas enables you to draw arbitrary graphics using a set of primitives, or "shapes", such as line, circle, arc, path and text. I bet you can even implement your own version of charts using Canvas control!

Combine Canvas with GestureDetector and you get a free-hand drawing app - Flet Brush ๐Ÿ˜€!

Example source

Canvas control is located in flet.canvas package. You need another import to use it:

import flet.canvas as cv

Here's a simple program drawing a smiley face with Circle and Arc shapes using filled and stroke Paint:

import math
import flet as ft
import flet.canvas as cv

def main(page: ft.Page):
stroke_paint = paint = ft.Paint(stroke_width=2, style=ft.PaintingStyle.STROKE)
fill_paint = paint = ft.Paint(style=ft.PaintingStyle.FILL)
cp = cv.Canvas(
[
cv.Circle(100, 100, 50, stroke_paint),
cv.Circle(80, 90, 10, stroke_paint),
cv.Circle(84, 87, 5, fill_paint),
cv.Circle(120, 90, 10, stroke_paint),
cv.Circle(124, 87, 5, fill_paint),
cv.Arc(70, 95, 60, 40, 0, math.pi, paint=stroke_paint),
],
width=float("inf"),
expand=True,
)

page.add(cp)

ft.app(main)

Read more about Canvas in docs and explore Canvas examples!

Other changesโ€‹

Rich text supportโ€‹

While working on drawing text on Canvas, as a bonus to this release, we implemented a new TextSpan control which can now be used with Text.spans to output rich text.

Check rich text examples: one, two and three.

url property for buttonsโ€‹

If you need to open a URL by clicking on a button or any other control with on_click event you can just provide that URL in url instead of doing that in the code with page.launch_url() method.

Instead of that:

ft.ElevatedButton("Go to Google", on_click=lambda e: e.page.launch_url("https://google.com"))

you can just do this:

ft.ElevatedButton("Go to Google", url="https://google.com")

A new url property also solves blocked window on Safari issue.

As a continuation of url property Markdown control can now be enabled to auto-follow URLs in the document:

import flet as ft

md = """
[Go to Google](https://www.google.com)
"""

def main(page: ft.Page):
page.add(
ft.Markdown(
md,
extension_set=ft.MarkdownExtensionSet.GITHUB_WEB,
auto_follow_links=True,
)
)

ft.app(main)

Better web supportโ€‹

In this release we also did some improvements to web support like capturing user info in page.client_id and page.client_user_agent as well as fixing nasty #1333 and #1289 bugs related to routing.

That's all for today!

Upgrade Flet module to the latest version (pip install flet --upgrade), give canvas and rich text a try and let us know what you think!

Flet Charts

ยท 2 min read
Feodor Fitsner
Flet founder and developer

Last year we introduced support for Matplotlib and Plotly charts. Both libraries are able to export charts as SVG images which are then displayed in a Flet app. However, such charts, while serving the purpose of visualization, are lacking interactivity and animation.

Today we are releasing Flet 0.5.2 with built-in charts ๐Ÿ“Š based on the awesome fl_chart library!

Three new chart controls have been introduced:

LineChartโ€‹

Docs ยท Examples

BarChartโ€‹

Docs ยท Examples

PieChartโ€‹

Docs ยท Examples

note

We spent a lot of time studying fl_chart library while trying to implement most of its features in a Flet way. However, if you see anything missing in Flet, but available in a library please submit a new feature request.

Other changesโ€‹

Pyodide 0.23โ€‹

Pyodide, which provides Python runtime in a browser and is used to run Flet app as a static website, was upgraded to version 0.23 which is based on Python 3.11.2 and giving some size and performance improvements.

Memory leak fixesโ€‹

In this release we paid a lot of attention to memory leak issues in Flet apps. Now, when a user session is closed its memory is reliably released and garbage-collected. That makes Flet ready for production applications with a lot of users.

Upgrade Flet module to the latest version (pip install flet --upgrade), give charts a try and let us know what you think!

Hey, Flet project has reached โญ๏ธ 5K stars โญ๏ธ - thank you all for your continuing support!

Standalone Flet web apps with Pyodide

ยท 4 min read
Feodor Fitsner
Flet founder and developer

We've just released Flet 0.4.0 with a super exciting new feature - packaging Flet apps into a standalone static website that can be run entirely in the browser! The app can be published to any free hosting for static websites such as GitHub Pages or Cloudflare Pages. Thanks to Pyodide - a Python port to WebAssembly!

You can quickly build awesome single-page applications (SPA) entirely in Python and host them everywhere! No HTML, CSS or JavaScript required!

Quick Flet with Pyodide demoโ€‹

Install the latest Flet package:

pip install flet --upgrade

Create a simple counter.py app:

counter.py
import flet as ft

def main(page: ft.Page):
page.title = "Flet counter example"
page.vertical_alignment = ft.MainAxisAlignment.CENTER

txt_number = ft.TextField(value="0", text_align=ft.TextAlign.RIGHT, width=100)

def minus_click(e):
txt_number.value = str(int(txt_number.value) - 1)
page.update()

def plus_click(e):
txt_number.value = str(int(txt_number.value) + 1)
page.update()

page.add(
ft.Row(
[
ft.IconButton(ft.icons.REMOVE, on_click=minus_click),
txt_number,
ft.IconButton(ft.icons.ADD, on_click=plus_click),
],
alignment=ft.MainAxisAlignment.CENTER,
)
)

ft.app(main)

Run a brand-new flet publish command to publish Flet app as a static website:

flet publish counter.py

The website will be published to dist directory next to counter.py. Give website a try using built-in Python web server:

python -m http.server --directory dist

Open http://localhost:8000 in your browser to check the published app.

Here are a few live Flet apps hosted at Cloudflare Pages:

Check the guide for more information about publishing Flet apps as standalone websites.

Built-in Fletd server in Pythonโ€‹

Flet 0.4.0 also implements a new Flet desktop architecture.

It replaces Fletd server written in Go with a light-weight shim written in Python with a number of pros:

  1. Only 2 system processes are needed to run Flet app: Python interpreter and Flutter client.
  2. Less communication overhead (minus two network hops between Python and Fletd) and lower latency (shim uses TCP on Windows and Unix domain sockets on macOS/Linux).
  3. Shim binds to 127.0.0.1 on Windows by default which is more secure.
  4. The size of a standalone app bundle produced by flet pack reduced by ~8 MB.

The implementation was also required to support Pyodide (we can't run Go web server in the browser, right?) and paves the way to iOS and Android support.

Other changesโ€‹

  • All controls loading resources from web URLs (Image.src, Audio.src, Page.fonts, Container.image_src) are now able to load them from local files too, by providing a full path in the file system, and from assets directory by providing relative path. For desktop apps a path in src property could be one of the following:
    • A path relative to assets directory, with or without starting slash, for example: /image.png or image.png. The name of artifact dir should not be included.
    • An absolute path within a computer file system, e.g. C:\projects\app\assets\image.png or /Users/john/images/picture.png.
    • A full URL, e.g. https://mysite.com/images/pic.png.
    • Add page.on_error = lambda e: print("Page error:", e.data) to see failing images.
  • flet Python package has separated into two packages: flet-core and flet.
  • PDM replaced with Poetry.
  • beartype removed everywhere.

๐Ÿ’ฅ Breaking changesโ€‹

  • Default routing scheme changed from "hash" to "path" (no /#/ at the end of app URL). Use ft.app(main, route_url_strategy="hash") to get original behavior.
  • OAuth authentication is not supported anymore in standalone desktop Flet apps.

Async supportโ€‹

Flet apps can now be written as async apps and use asyncio with other Python async libraries. Calling coroutines is naturally supported in Flet, so you don't need to wrap them to run synchronously.

To start with an async Flet app you should make main() method async:

import flet as ft

async def main(page: ft.Page):
await page.add_async(ft.Text("Hello, async world!"))

ft.app(main)

Read the guide for more information about writing async Flet apps.

Conclusionโ€‹

Flet 0.4.0 brings the following exciting features:

  • Standalone web apps with Pyodide running in the browser and hosted on a cheap hosting.
  • Faster and more secure architecture with a built-in Fletd server.
  • Async apps support.

Upgrade Flet module to the latest version (pip install flet --upgrade), give flet publish command a try and let us know what you think!

Hey, by the way, Flet project has reached โญ๏ธ 4.2K stars โญ๏ธ (+1K in just one month) - keep going!

Packaging desktop apps with a custom icon

ยท One min read
Feodor Fitsner
Flet founder and developer

Happy New Year! Flet project has reached โญ๏ธ 3.3K stars โญ๏ธ on GitHub which is very exciting and encouraging! Thank you all for your support!

We are starting this year with the release of Flet 0.3.2 bringing a long-awaited feature: creating standalone desktop bundles with a custom icon!

flet command has been used for running Flet program with hot reload, but we recently re-worked Flet CLI to support multiple actions.

There is a new flet pack command that wraps PyInstaller API to package your Flet Python app into a standalone Windows executable or macOS app bundle which can be run by a user with no Python installed.

Command's --icon argument is now changing not only executable's icon, but Flet's app window icon and the icon shown in macOS dock, Windows taskbar, macOS "About" dialog, Task Manager and Activity Monitor:

Bundle name, version and copyright can be changed too:

Find all available options for packaging desktop apps in the updated guide.

Upgrade Flet module to the latest version (pip install flet --upgrade), give flet pack command a try and let us know what you think!

Flet mobile update

ยท 5 min read
Feodor Fitsner
Flet founder and developer

This post is a continuation of Flet mobile strategy published a few months ago.

Our original approach to Flet running on a mobile device was Server-Driven UI. Though SDUI has its own benefits (like bypassing App Store for app updates) it doesn't work in all cases, requires web server to host Python part of the app and, as a result, adds latency which is not great for user actions requiring nearly instance UI response, like drawing apps.

I've been thinking on how to make Python runtime embedded into Flutter iOS or Android app to run user Python program. No doubt, it's technically possible as Kivy and BeeWare projects do that already.

Current Flet architectureโ€‹

The current architecture of Flet desktop app is shown on the diagram below:

Running Flet program on a desktop involves three applications (processes) working together:

  • Python runtime (python3) - Python interpreter running your Python script. This is what you are starting from a command line. Python starts Fletd server and connects to it via WebSockets.
  • Fletd server (fletd)- Flet web server written in Go, listening on a TCP port. Fletd holds the state of all user sessions (for desktop app there is only one session) and dispatches page updates and user generated events between Python program and Flet client.
  • Flet client (flet) - desktop app written in Flutter and displaying UI in a native OS window. Flet client connects to Fletd server via WebSockets.

The architecture above works well for Flet web apps where web server is essential part, but for desktop it seems redundant:

  • If all three processes run on the same computer WebSockets could be replaced with sockets or named pipes with less overhead.
  • Fletd server has no much sense as there is only one user session and UI state is persistently stored in Flet desktop client which is never "reloaded".

Flet new desktop architectureโ€‹

Flet desktop app architecture can be simplified by replacing Fletd with a "stub" written in Python and communicating with Flet desktop client via sockets (Windows) and named pipes (macOS and Linux):

Flet mobile architectureโ€‹

Mobile applications are running in a very strict context with a number of limitations. For example, on iOS the app cannot spawn a new processes. Other words, Flet Flutter app cannot just start "python.exe" and pass your script as an argument.

Luckily for us, Python can be embedded into another app as a C library and Dart (the language in which Flutter apps are written) allows calling C libraries via FFI (Foreign Function Interface).

Additionally, while Android allows loading of dynamically linked libraries iOS requires all libraries statically linked into app executable. This article covers Dart FFI in more details, if you are curious.

Flet mobile architecture could look like this:

Python runtime will be statically or dynamically linked with Flutter client app and called via FFI and/or named pipes.

Running Python on mobile will have some limitations though. Most notable one is the requirement to use "pure" Python modules or modules with native code compiled specifically for mobile ARM64 architecture.

Asyncio supportโ€‹

Asyncio is part of Python 3 and we start seeing more and more libraries catching up with async/await programming model which is more effective for I/O-bound and UI logic.

Currently, Flet is spawning all UI event handlers in new threads and it's also a pain to see threading.sleep() calls hogging threads here and there just to do some UI animation. All that looks expensive.

Using of async libraries from a sync code is possible, but looks hacky and inefficient as it keeps CPU busy just to wait async method to finish. So, we want a first-class support of async code in Flet app.

Async/await model is a state machine switching between tasks in a single thread. By going async Flet will able to utilize streams for socket server and use async WebSockets library library. It will be possible to use both sync and async event handlers in a single Flet app without any compromises or hacks.

Even more exciting, async Flet will be able to run entirely in the browser within Pyodide - Python distribution based on WebAssembly (WASM). WebAssembly doesn't have multi-threading support yet, so running in a single thread is a must. Just imagine, Flet web app with a truly offline Flet PWA that does not require a web server to run a Python code!

Development planโ€‹

We are going to crunch the scope above in a few iterations:

  1. Async API support with async WebSockets library. Works with the same Fletd in Go.
  2. Fletd server ("stub") in Python to use with a desktop.
  3. Embedding Python with Fletd "stub" and user program into iOS.
  4. Embedding Python into Android.
  5. Packaging mobile apps for iOS and Android.
HELP WANTED

๐Ÿ™ I'm looking for a help from the community with developing C/C++/native code integration part between Flutter and Python on iOS and Android. It could be either free help or a paid job - let me know if you are interested!

Hop to Discord to discuss the plan, offer help, ask questions!