RFP: Async support in Flet Python client
See original GitHub issueDiscussed in https://github.com/flet-dev/flet/discussions/72
Problem
It is currently impossible to call async method from Flet event handlers. They are synchronous functions run in separate threads. This limitation requires to use bulky constructs like:
search_data = new_event_loop().run_until_complete(get_weather(search_value))
where get_weather(search_value) is async function.
Solution
As in other languages like C# a “proper” async must be implemented from ground up - it’s impossible/ineffective to partially support calling async methods from sync ones. The entire program must be running in an event loop (in Python terms).
Flet Python client must be re-implemented to use asyncio library.
Sample code
Flet client will be providing both sync and async methods, for example async version of “Hello, world” might look like:
import asyncio
import flet as ft
async def main(page: ft.Page):
async def btn_click(e):
var result = await some_call_to_rest_api()
page.controls.append(ft.Text(result))
await page.update_async()
await page.add_async(
ft.Text("Hello!"),
ft.ElevatedButton("Call async method", on_click=btn_click)
)
ft.app(target=main)
All async methods will have _async suffix.
WebSockets client will be implemented with websockets library based on asyncio.
Resources:
Flet API
Sync is going to be default style of writing Flet apps. Flet API that needs to be available in both sync and async variants:
Connectionclass - have a baseConnectionclass and two implementations:SyncConnectionandAsyncConnection:def connect()async def connect_async()def send_command(self, session_id: str, command: Command)async def send_command_async(self, session_id: str, command: Command)def send_commands(self, session_id: str, commands: List[Command])async def send_commands_async(self, session_id: str, commands: List[Command])def close(self)on_event- could be eitherCallableorCoroutineon_session_created- could be eitherCallableorCoroutineReconnectingWebSocketmust be created insideSyncConnection.- Can we use
send_commandsonly in all cases?
Pageclass:- TBD
Issue Analytics
- State:
- Created a year ago
- Reactions:4
- Comments:7 (4 by maintainers)

Top Related StackOverflow Question
We go ahead with Async support in Flet: https://flet.dev/blog/flet-mobile-update#asyncio-support
How wonderful, thanks! 😃