Error when listing results on screen using Flet and Python

Good morning! I don’t know if anyone has encountered this problem. I created a logic to search for the result of a query in the database and list in the application using flet a checkbox with a list of notes for the user to mark and proceed with a signature. However, even when debugging, obtaining the results of the nfes and user_cpf variables correctly when running the code, I cannot view them on the screen using flet.

selected_nfes = # Inicializa a lista de NFEs selecionadas

def on_nfe_checked(e, nfe):

    if e.control.value:

        selected_nfes.append(nfe)

    else:

        selected_nfes.remove(nfe)



def get_nfe_list(user_cpf):

    if user_cpf is None:

        raise ValueError("user_cpf is None")

    user_cpf = re.sub(r'\D', '', user_cpf)  # Remove caracteres não numéricos

    conn = connect_to_db()

    cursor = conn.cursor()

    query = """

        SELECT e140ide.ChvDoe, e140ide.NumNfv, e140ide.CodEmp, e140ide.CodFil, e140ide.CodSnf, e073mot.CgcCpf, e073mot.NomMot

        FROM e140ide

        INNER JOIN e140nfv ON e140ide.NumNfv = e140nfv.NumNfv AND e140ide.CodEmp = e140nfv.CodEmp AND e140ide.CodFil = e140nfv.CodFil AND e140ide.CodSnf = e140nfv.CodSnf

        INNER JOIN e073mot ON e140nfv.CodMtr = e073mot.CodMtr AND e140nfv.TraMtr = e073mot.CodTra

        WHERE e140nfv.DatEmi >=  DATEADD(DAY, -10, GETDATE()) AND e073mot.CgcCpf = ?

        ORDER BY e140ide.CodEmp, e140ide.NumNfv

        """

    cursor.execute(query, user_cpf) #print(f"Executing query with user_cpf no get_nfe_list: {user_cpf}")  # Para debug

    nfes = cursor.fetchall()

    conn.close()

    return nfes    



def create_nfe_controls(nfes):

    nfe_controls = []

    for nfe in nfes:

        nfe_checkbox = ft.Checkbox(value=False, on_change=lambda e, n=nfe: on_nfe_checked(e, n))

        nfe_control = ft.Row([

            nfe_checkbox,

            ft.Column([

                ft.Text(f"Nota: {nfe.NumNfv} - Empresa: {nfe.CodEmp}"),

                ft.Text(f"Chave: {nfe.ChvDoe}")

            ])

        ])

        nfe_controls.append(nfe_control)

    return nfe_controls



def show_nfe_list(e):

    try:

        if user_cpf is None:

            raise ValueError("O CPF do usuário não foi obtido.")

        print(f"Show NFE List - CPF: {user_cpf}")  # Debug

        nfes = get_nfe_list(user_cpf)

        print(f"NFEs returned: {len(nfes)}")  # Debug

        if len(nfes) == 0:

            raise ValueError("Nenhuma NFE encontrada para o usuário.")

       

        nfe_controls = create_nfe_controls(nfes)

       

        page.controls.clear()

        page.add(

            ft.Column([

                ft.Container(

                    content=ft.ListView(controls=nfe_controls, spacing=10),

                    height=600,  # Ajuste conforme necessário para permitir rolagem

                    scroll=ft.ScrollMode.ALWAYS

                ),

                ft.ElevatedButton(text="Prosseguir", on_click=show_cpf_input)

            ], alignment=ft.MainAxisAlignment.CENTER, horizontal_alignment=ft.CrossAxisAlignment.CENTER)

        )

        page.update()

    except ValueError as ve:

        page.snack_bar = ft.SnackBar(content=ft.Text(f"Erro: {ve}"))

        page.snack_bar.open = True

    except Exception as ex:

         # Registrar o erro em um arquivo de log

        with open("errors.log", "a") as log_file:

            log_file.write(f"Erro inesperado: {ex}\n")

        page.snack_bar = ft.SnackBar(content=ft.Text(f"Erro inesperado: {ex}"))

        page.snack_bar.open = True