我有一个列表,我想根据用户在搜索栏中输入的内容来过滤其项目。假设用户在搜索栏中输入“o”。在这种情况下,我想更新 ListTile 以仅显示名称中包含子字符串“o”的水果。我的代码是:
import flet as ft
fruits_list = ["apple", "banana", "orange", "grape", "strawberry", "watermelon", "kiwi", "pineapple", "mango", "pear"]
list_to_show = fruits_list
def main(page):
global list_to_show
def handle_change(e):
global list_to_show
list_to_show = [i for i in fruits_list if e.data in i]
anchor = ft.SearchBar(
view_elevation=4,
divider_color=ft.colors.BLUE,
bar_hint_text="Search for fruits...",
view_hint_text="Suggestions...",
on_change=handle_change,
controls=[
ft.ListTile(title=ft.Text(f"{i}"), data=i)
for i in list_to_show
],
)
page.add(
ft.Row([
anchor
],
alignment=ft.MainAxisAlignment.CENTER
)
)
ft.app(target=main, view=ft.AppView.WEB_BROWSER)
问题是:ListTile 只显示list_to_show 的第一个值。我尝试了以下方法,但没有成功:
def handle_change(e):
global list_to_show
list_to_show = [i for i in fruits_list if e.data in i]
anchor.controls.clear()
for item in list_to_show:
anchor.controls.append(ft.ListTile(title=ft.Text(f"{item}"), on_click=close_anchor, data=item))
anchor.update()
问题在于你在
SearchBar
的构造函数中创建了
ListTile
控件。这样只会创建一次控件,并且不会在
handle_change
函数中更新。
为了解决这个问题,你需要在
handle_change
函数中动态创建
ListTile
控件,并将它们添加到
SearchBar.controls
列表中。
以下是修改后的代码:
import flet as ft
fruits_list = ["apple", "banana", "orange", "grape", "strawberry", "watermelon", "kiwi", "pineapple", "mango", "pear"]
def main(page):
def handle_change(e):
# 根据搜索内容过滤 fruits_list
filtered_fruits = [i for i in fruits_list if e.data.lower() in i.lower()]
# 清空现有控件
search_bar.controls.clear()
# 添加新的 ListTile 控件
for item in filtered_fruits:
search_bar.controls.append(ft.ListTile(title=ft.Text(f"{item}")))
# 更新界面
search_bar.update()
search_bar = ft.SearchBar(
view_elevation=4,
divider_color=ft.colors.BLUE,
bar_hint_text="Search for fruits...",
view_hint_text="Suggestions...",
on_change=handle_change,
controls=[], # 初始化为空列表
)
page.add(
ft.Row([
search_bar
],
alignment=ft.MainAxisAlignment.CENTER
)
)
ft.app(target=main, view=ft.AppView.WEB_BROWSER)
解释:
-
初始化
controls
为空列表: 在创建SearchBar
时,我们将其controls
属性初始化为空列表。 -
在
handle_change
中动态创建控件: 每次搜索内容改变时,handle_change
函数都会被调用。在该函数中,我们首先根据搜索内容过滤fruits_list
。然后,我们使用search_bar.controls.clear()
清空现有的ListTile
控件。接下来,我们循环遍历过滤后的水果列表,并为每个水果创建一个新的ListTile
控件,并将其添加到search_bar.controls
列表中。 -
调用
search_bar.update()
: 最后,我们调用search_bar.update()
函数来更新SearchBar
控件,以便显示新的ListTile
控件。
通过这种方式,每次搜索内容改变时,
SearchBar
都会显示更新后的水果列表。