首页 > 编程问答 >更新flet中SearchBar的ListTile

更新flet中SearchBar的ListTile

时间:2024-07-28 13:55:52浏览次数:7  
标签:python flutter flet

我有一个列表,我想根据用户在搜索栏中输入的内容来过滤其项目。假设用户在搜索栏中输入“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)

解释:

  1. 初始化 controls 为空列表: 在创建 SearchBar 时,我们将其 controls 属性初始化为空列表。
  2. handle_change 中动态创建控件: 每次搜索内容改变时, handle_change 函数都会被调用。在该函数中,我们首先根据搜索内容过滤 fruits_list 。然后,我们使用 search_bar.controls.clear() 清空现有的 ListTile 控件。接下来,我们循环遍历过滤后的水果列表,并为每个水果创建一个新的 ListTile 控件,并将其添加到 search_bar.controls 列表中。
  3. 调用 search_bar.update() : 最后,我们调用 search_bar.update() 函数来更新 SearchBar 控件,以便显示新的 ListTile 控件。

通过这种方式,每次搜索内容改变时, SearchBar 都会显示更新后的水果列表。

标签:python,flutter,flet
From: 78288882

相关文章

  • python第五节--conda命令
    这里写自定义目录标题基本命令环境管理包管理环境文件环境变量Conda配置高级操作常见问题基本命令检查Conda版本:conda--version更新Conda:condaupdateconda环境管理创建新环境:condacreate--namemyenv创建包含特定Python版本的新环境:conda......
  • 如何使用python向另一台计算机发送请求
    基本上我有一个聊天室,我将把它变成一个网络(我知道这听起来没有多大意义),但基本上我想知道是否可以让python脚本捕获计算机上的所有传出请求并将其发送到另一台计算机(c2)。然后我希望c2自己发出请求。这是对我正在做的事情的淡化解释,但任何帮助都会很棒!当然可以!虽然从头......
  • AttributeError:'int'对象没有属性'index'(python)
    我正在Python上进行“猜单词”,但我无法弄清楚这个错误。AttributeError:'int'objecthasnoattribute'index'(python)它在线上给了我一个错误letterIndex=word.index(guess)defcheckLetter(word):blanks='_'*len(str(word))print('W......
  • 尝试在Python中使用for循环来输出大于或等于序列中的数字
    这是我的Python代码:largest_so_far=-1print('before',largest_so_far)forthe_numin[9,41,12,3,74,15]:ifthe_num>largest_so_far:largest_so_far=the_numprint(largest_so_far,'isbiggerthan',the_num)......
  • 如何在 wxPython 的 for 循环中添加文本输入框?
    我是wxPython的新手,正在开发一个带有GUI的基本程序,让用户标记图像。现在,当用户单击“导入”按钮时,他们可以选择一个目录。然后,代码使用matplotlib在for循环中显示该目录中的每个图像。但是,我不知道如何在for循环中访问用户输入。这就是该函数现在的样子:importmatplo......
  • 【Python】字母 Rangoli 图案
    一、题目YouaregivenanintegerN.YourtaskistoprintanalphabetrangoliofsizeN.(RangoliisaformofIndianfolkartbasedoncreationofpatterns.)Differentsizesofalphabetrangoliareshownbelow:#size3----c------c-b-c--c-b-a-b-c--c......
  • python 闭包、装饰器
    一、闭包:1.外部函数嵌套内部函数 2.外部函数返回内部函数 3.内部函数可以访问外部函数局部变量         闭包(Closure)是指在一个函数内部定义的函数,并且内部函数可以访问外部函数的局部变量,即使外部函数已经执行完毕,这种现象称为闭包。在Python中,闭包常常用......
  • 掌握 IPython %%time 魔法命令:高效测量代码块执行时间
    引言在编程和数据分析中,了解代码的执行时间是优化性能的关键步骤。IPython,作为一个强大的交互式计算环境,提供了多种工具来帮助用户测量和优化代码。其中,%%time魔法命令是IPython中用来测量代码块执行时间的便捷工具。本文将详细介绍%%time魔法命令的使用方法,并通过一......
  • 探索 IPython 中的 %%javascript 魔法命令:运行 JavaScript 代码的秘籍
    引言IPython是一个强大的交互式计算环境,它不仅支持Python语言,还通过各种魔法命令扩展了其功能。其中,%%javascript魔法命令是IPython扩展中一个非常有趣的特性,它允许用户在IPython环境中直接运行JavaScript代码。这对于需要在数据科学和科学计算中使用JavaScript......
  • pythonasm库分析,看看你和自学编程小学生的差距
    下面是pythonasm.asm库的源代码fromkeystoneimport*fromcapstoneimport*assembly_instructions=[]#储存汇编指令的列表#汇编指令写入列表defmov(reg1,reg2):assembly_instructions.append(f"mov{reg1},{reg2}")defdb(value):assembly_instructio......