AsyncIO not working on android (APK)
Duplicate Check
- [x] I have searched the opened issues and there are no duplicates
Describe the bug
Hi! The problem I have is that when I package my app in APK, if I declare the "asyncio" package as a dependency of my project in "pyproject.toml", the app doesn't open. It gets stuck on a post-splash screen but pre-launches the app or first view. (normal theoretical start order: 1-click on the app | 2-splash | 3-dark/light theme color screen | 4-launches the first view of the app). Minutes and even hours go by and that dark/light screen doesn't go any further.
If I don't declare "asyncio" in my "pyproject.toml" but I keep using it in other scripts/views, when I want to run that view, it gets stuck just like it used to when I declared it. Only in this case, it's when you want to use asyncio, for example with "await asyncio.to_thread(MyAPI().api_query_function)".
Testing a bit, I realized that it does not start when the requirement to start depends exclusively on an asyncio function, in my particular case as you will see below in the attached codes, it is when it hits the API by consulting the local file.
In the codes that I will leave below, the problem occurs in two cases:
1- If the user has already logged in previously, therefore, the part of the "main.py" code runs where it searches for the user information in the API using the contents of the local file.
2- If the user logs in, assuming a first start where there is no saved local file, when trying to start the "home.py" view, after the "login.py" one. In "home.py" the API is consulted, for this example, the user name is consulted to place it in a Text().
Code sample
Code
pyproject.toml:
[tool.poetry.dependencies]
python="^3.11"
[project]
dependencies = [
"flet-audio",
"flet_ads",
"flet>=0.26.0",
"python-dotenv>=1.0.1",
"requests",
"asyncio"
]
main.py
from flet import *
from dotenv import load_dotenv
from components.audio_control import AudioControls
from components.layout import Layout
from components.api_client import APIClient
import os, json, asyncio
class AppRouter:
def __init__(self, page):
self.page = page
self.routes = {
"/": self.login_view,
"/home": self.home_view,
"/descubrir": self.descubrir_view,
"/playlists": self.playlists_view,
"/academia": self.academia_view,
"/mi-perfil": self.mi_perfil_view,
}
self.audio_controls = AudioControls(page)
self.layout = Layout(page, self.audio_controls) # Instanciar el diseño principal
async def load_user_from_storage(self):
storage_dir = os.getenv("FLET_APP_STORAGE_DATA", "./app_data")
user_data_file = os.path.join(storage_dir, "user_data.json")
if os.path.exists(user_data_file):
try:
with open(user_data_file, "r") as f:
user_data = json.load(f)
print(f"Datos del usuario cargados: {user_data}")
# Guardar en client_storage
self.page.client_storage.set("token", user_data["token"])
api_client = APIClient(token=self.page.client_storage.get("token"))
user_info = await asyncio.to_thread(api_client.get_user_info)
# Guardar datos en `client_storage`
for key in ["id", "username", "email", "full_name", "membership_status"]:
self.page.client_storage.set(key, user_info.get(key, ""))
# Redirigir al Home
self.page.go("/home")
except Exception as e:
print(f"Error al cargar usuario: {e}")
self.page.go("/")
else:
# Mostrar pantalla de inicio de sesión
self.page.go("/")
def login_view(self):
from views.login import Login
return Login(self.page).build()
def home_view(self):
from views.home import Home
return Home(self.page, self.layout, self.audio_controls).build()
def descubrir_view(self):
from views.descubrir import Descubrir
return Descubrir(self.page, self.layout, self.audio_controls).build()
def playlists_view(self):
from views.playlists import Playlists
return Playlists(self.page, self.layout, self.audio_controls).build()
def academia_view(self):
from views.academia import Academia
return Academia(self.page, self.layout, self.audio_controls).build()
def mi_perfil_view(self):
from views.mi_perfil import MiPerfil
return MiPerfil(self.page, self.layout, self.audio_controls).build()
def navigate(self, route):
if route == "/":
self.page.views.clear()
self.page.views.append(self.routes[route]())
self.page.update()
else:
if route in self.routes:
self.page.views.clear()
self.audio_controls.set_page(self.page)
self.page.views.append(self.layout.build(self.routes[route]()))
self.page.update()
def main(page: Page):
load_dotenv()
page.title = "Manifestapp"
page.theme_mode = ThemeMode.DARK
page.fonts = {
"Kanit": "https://raw.githubusercontent.com/google/fonts/master/ofl/kanit/Kanit-Bold.ttf",
"Poppins Regular": "/fonts/poppins/Poppins-Regular.ttf",
"Poppins Bold": "/fonts/poppins/Poppins-Bold.ttf",
"Poppins Italic": "/fonts/poppins/Poppins-Italic.ttf",
}
page.theme = Theme(font_family="Poppins Regular")
router = AppRouter(page)
page.run_task(router.load_user_from_storage)
def on_route_change(e):
router.navigate(page.route)
page.on_route_change = on_route_change
app(main, assets_dir="assets")
home.py:
from flet import *
from components.api_client import APIClient
import os, asyncio
class Home:
def __init__(self, page, layout, audio_controls):
self.page = page
self.layout = layout
self.audio_controls = audio_controls
self.page.run_task(self.validate_token_async)
async def validate_token_async(self):
"""Validación asíncrona del token para evitar bloqueos en la UI."""
api_client = APIClient(token=self.page.client_storage.get("token"))
try:
await asyncio.to_thread(api_client.get_user_info)
except Exception as e:
print(f"Token inválido: {e}")
storage_dir = os.getenv("FLET_APP_STORAGE_DATA", "./app_data")
user_data_file = os.path.join(storage_dir, "user_data.json")
if os.path.exists(user_data_file):
os.remove(user_data_file)
self.page.go("/")
def build(self):
username = self.page.client_storage.get("username") or "Usuario"
return Column(
[
Text(f"¡Bienvenido, {username}!", size=24, weight=FontWeight.BOLD),
Text("Comienza explorando contenido nuevo o escuchando tus playlists.", size=16),
],
alignment=MainAxisAlignment.CENTER,
expand=True,
)
To reproduce
"asyncio" in [project] dependencies -> "pyproject.toml" or the use of the same.
Expected behavior
It remains frozen.
Screenshots / Videos
Captures
Operating System
Windows
Operating system details
Windows 11
Flet version
0.26.0
Regression
No, it isn't
Suggestions
No response
Logs
Logs
[Paste your logs here]
Additional details
No response
It closes due to bad programming. Asyncio and aiohttp work correctly on Android.