bug: Creating a large list in ListView by referencing custom components through a for loop causes extreme lag.
Duplicate Check
- [x] I have searched the opened issues and there are no duplicates
Describe the bug
Creating a large list in ListView by referencing custom components through a for loop causes extreme lag. This issue did not exist in version 0.28.
Code sample
Code
[Paste your code here]
To reproduce
import flet as ft
class 分镜列表UI: def init(self,page:ft.Page) -> None: self.page=page self.按钮栏颜色="#222222" self.容器背景="#2D2D2D"
self.高度=260
self.间距=5
def 定义(self):
return ft.Container(
expand=True, # 改为 expand=True 而不是 height=True
# bgcolor="#000000",
alignment=ft.Alignment.CENTER,
# width=300,
content=ft.Row(controls=[
ft.Container(
# width=1270,
content=self.分镜列表()
),
ft.Container(expand=True)
])
)
def 分镜列表(self):
list_items=[]
列表=ft.ListView(
controls=list_items,
spacing=5, # 添加间距
padding=5, # 添加内边距
expand=True # ListView 需要 expand=True
)
a=ft.Container(content=ft.TextButton("sd",on_click=lambda e
:print("asdfadfadfadfasdfasd")))
for i in range(1, 300):
# 第一部分
图片生成预览器= a
背景图片预览器= a
姿态图片预览器= a
参考图=ft.Row(spacing=self.间距,
controls=[
背景图片预览器,
姿态图片预览器
]
)
字幕预览器组件=a
字幕预览器组件.width=self.page.width
台词数据=a
台词预览_台词=ft.Container(padding=5,expand=True)
台词列表=ft.Column(controls=[])
# if 台词数据:
# for i in 台词数据:
# 台词列表.controls.append(ft.Text(f"{i["发言人"]}:{i["台词"]}",size=10))
# 台词预览_台词.content=台词列表
# else:
台词预览_台词.content=ft.Container(alignment=ft.Alignment.CENTER,content=ft.Text("台词预览器[空]"))
台词预览_按钮栏= a
台词预览布局=ft.Column(spacing=0,
controls=[
# ft.FilledButton("编辑台词", icon=ft.Icons.ADD_OUTLINED),
台词预览_台词,
台词预览_按钮栏
]
)
台词预览器=ft.Container( expand=True,
width=(self.高度*0.4*2)+self.间距,
height=self.高度-(self.高度*0.4)-self.间距,
border = ft.Border.all(1,"#26634C"),border_radius=5,
bgcolor=self.容器背景,alignment=ft.Alignment.CENTER,content=ft.Text("台词"))
台词预览器.content=台词预览布局
# 第二部分
第二部分内容=ft.Column(spacing=self.间距,expand=True,controls=[参考图,台词预览器])
图片文件上传预览= a
图片文件上传预览容器= ft.Container(height=self.高度*0.2,bgcolor=self.容器背景,
# border_radius=5,
border=ft.Border.only(bottom=ft.BorderSide(1, "#26634C")),
alignment=ft.Alignment.CENTER,content=图片文件上传预览)
文本输入框=ft.TextField(
value="",
border_radius=0,
#设置边框为透明
border_color=ft.Colors.TRANSPARENT,
# cursor_color="#FFFFFF",
# color="#FFFFFF",
#设置背景色
bgcolor=self.容器背景,
# 文字大小
text_size=14,
multiline=True,
min_lines=100,
expand=True,
)
按钮栏= ft.Container(height=35,bgcolor=self.按钮栏颜色,
content=ft.Row(spacing=0,
controls=[
ft.IconButton(
icon=ft.Icons.SETTINGS_APPLICATIONS_ROUNDED,
tooltip="设置",
icon_size=20,
icon_color="#000000",
),
ft.Container(expand=True),
ft.IconButton( icon=ft.Icons.IMAGE,tooltip="上传参考图",icon_size=20,icon_color="#000000",
),
ft.FilledButton(content="发送", icon=ft.Icons.SEND_ROUNDED,height=27,bgcolor="#26634C"),
]
))
提示词输入控件布局=ft.Column(spacing=0,
expand=True,
controls=[
图片文件上传预览容器,
文本输入框,
按钮栏
]
)
提示词输入控件=ft.Container(
# width=True,
width=self.高度*1.5,
height=self.高度, border = ft.Border.all(1,"#26634C"),border_radius=5,)
提示词输入控件.content=提示词输入控件布局
#添图片生成预览器
组件布局=ft.Row(spacing=5,
#expand=True
)
组件容器=ft.Container( #bgcolor="#B67878",
expand=True)
组件容器.content=组件布局
组件容器.content.controls.append(图片生成预览器)
组件容器.content.controls.append(第二部分内容)
组件容器.content.controls.append(提示词输入控件)
# 为每个列表项创建独立的组件实例
分镜生成组件 = 组件容器
列表.controls.append(分镜生成组件)
if i % 5 == 0:
self.page.update()
return 列表
class 分镜列表页面: def init(self) -> None:
pass
def 分镜列表(self):
for i in range(1, 20):
yield ft.Container(
content=ft.Column(
controls=[ ft.Container()]
)
)
def 构建UI(self):
return ft.Container(
content=ft.Column(
controls=[
ft.ListView()
]
)
)
if name == "main": def main(page: ft.Page): # 设置页面尺寸
page.add(分镜列表UI(page).定义())
ft.run(main)
Expected behavior
No response
Screenshots / Videos
Captures
[Upload media here]
Operating System
Windows
Operating system details
11
Flet version
0.8
Regression
No, it isn't
Suggestions
No response
Logs
Logs
[Paste your logs here]
Additional details
No response
A similar issue also occurred in Datatable2. This issue was firstly discovered at Flet 0.70.0. It is speculated that in the new version of Flet, each element in a cell has been implemented as a separate instance.
This issue was firstly discovered at Flet 0.70.0. It is speculated that in the new version of Flet, each element in a cell has been implemented as a separate instance.
Hi, so how can I avoid this lag?
Pray that the developers of Flet have a great mercy and remember to optimize this logic, or find a way to reduce the number of individual objects you create :)
But if it were me, I also wouldn't think that using a for loop to create so many Rows, Containers or something else is a good idea.
But if it were me, I also wouldn't think that using a for loop to create so many
Rows,Containers or something else is a good idea.
Thank you for the suggestion. I will try it out.
Got a solution ?
有解决办法吗?
There is currently no better method, but disabling refresh can help alleviate the issue。Turn off automatic refresh
Heaving the same issue with a log streamer implementation with flet v0.80+( a Listview wich is dynamic upated in the background with more Text controls (log lines) ) and the ability to search this controls to highlight the lines the searchterm was found is nearly unusable.
Looping over the controls in the listview takes ages even there are only not much controls in it. Application is completly unresponsible (its async code and even the log streaming runs as background task)
Same implematation runs in flet 0.28.3 really fast with thousands of controls inside the listview. @FeodorFitsner .. hope you can help. If you need something let me know. Thanks in advanced!
@NiTRoeSE do you have a simple repro for both 0.28 and 0.80?
@NiTRoeSE do you have a simple repro for both 0.28 and 0.80?
Sorry for delay answering..
Yes i´ve written / extracted a minimal working example from my code and recognized with this example that it runs smooth and fast overall. That was a bit annyoing ;).
So i investigated the last 2 days to get the differnce between the original code and the example. After a lot of testing and rewriting varius things and test another approaches i recognized that something on my side blocks something wich leads to a extremly laggy ui and produce the issue.
After a lot more testing i finally found my fault. The logs i talked about are retrieved via ssh (paramiko) in the following way (example / snipped):
self.cmd = f'cd /docker/{self.stack_name} && docker-compose logs -f --tail 10'
stdin, stdout, stderr = self.client.exec_command(self.cmd, get_pty=True)
for line in iter(stdout.readline, ""):
self.line_control = ft.Text(
escape_ansi(line=line),
style = ft.TextStyle(font_family="RobotoMono"),size=12,
selectable=True,
)
self.response_list.controls.append(
self.line_control
)
# if list is to long search takes a lot of time .. so we pop controls out of responselist
if self.line_count >= 2001:
self.response_list.controls.pop(0)
self.line_count = self.line_count - 1
self.response_list.update()
if not line:
self.logger.info("Finished log streaming. 22")
break
This way paramiko blocks .. i have no clue why this runs smooth and not blocking with flet 0.28.3 but in 0.80+ it blocks the whole ui long and longer the log streaming runs.
Implementing the log streaming in the following way (non blocking) completly resolves my issue.
self.cmd = f'cd /docker/{self.stack_name} && docker-compose logs -f --tail 10'
self.transport = self.client.get_transport()
self.channel = self.transport.open_session()
self.channel.settimeout(0.0) # no blocking
self.channel.exec_command(self.cmd)
buffer = ""
while self.log_stream_running == True:
if self.channel.recv_ready():
data = self.channel.recv(1024).decode('utf-8')
buffer += data
while '\n' in buffer:
line, buffer = buffer.split('\n', 1)
self.line_control = ft.Text(
escape_ansi(line=line),
style = ft.TextStyle(font_family="RobotoMono"),size=12,
selectable=True,
)
self.response_list.controls.append(self.line_control)
# if list is to long search takes a lot of time .. so we pop controls out of responselist
if self.line_count >= 2001:
self.response_list.controls.pop(0)
self.line_count = self.line_count - 1
self.response_list.update()
if self.channel.exit_status_ready():
self.log_stream_running = False
break
await asyncio.sleep(0.1) # Reduce cpu load ...
So I assume that the biggest delay problems come from code that did not cause significant delays with 0.28.3, but has always caused delays, only that this was hardly noticeable or not noticeable at all.
It would be great if anybody can explain this behavior between 0.28.x and 0.80.x just for learning and understanding it better. In any case, my problem was not a flet problem.
Thanks for your investigation! (...and fixing the dropdown expand :) )
This is fundamental difference between Flet 0.28 and 0.80 - it's now a pure async library which means it's running in a single thread and any blocking operation blocks UI.
If it's IO-bound logic you should see if it could be rewritten into async/await using async equivalents of your favorite libraries.
If it's CPU-bound logic you can offload it to a thread, for example:
import asyncio
import time
def cpu_work(x: int) -> int:
time.sleep(5) # for brevity
return x * x # placeholder
async def main():
result = await asyncio.to_thread(cpu_work, 123)
print(result)
asyncio.run(main())
I'm leaving this issue open as a reminder to myself that we have to reflect this in the documentation as it's very important.