flet-dev / flet

Flet enables developers to easily build realtime web, mobile and desktop apps in Python. No frontend experience required.
https://flet.dev
Apache License 2.0
9.59k stars 372 forks source link

custom control with ref error #3254

Closed BrentHuang closed 3 weeks ago

BrentHuang commented 3 weeks ago

Please Describe The Problem To Be Solved

on windows 10, flet 0.22.0, my code:

# -*- coding: utf-8 -*-

from typing import Any
import flet as ft

class PickFilesDialog(ft.FilePicker):

    def __init__(self) -> None:
        super().__init__()
        self.ref = file_picker
        self.on_result = self.pick_files_result

    def pick_files_result(self, e: ft.FilePickerResultEvent):
        str = (", ".join(map(lambda f: f.name, e.files)) if e.files else "Cancelled!")
        print(str)
        str = (", ".join(map(lambda f: f.path, e.files)) if e.files else "Cancelled!")
        print(str)

file_picker = ft.Ref[PickFilesDialog]()

def main(page: ft.Page):

    def pick_file_dialog(e):
        file_picker.current.pick_files()

    page.add(ft.ElevatedButton('open', on_click=pick_file_dialog))
    page.overlay.append(PickFilesDialog())

ft.app(target=main)

when click 'open' button, it raise:

Future exception was never retrieved
future: <Future finished exception=AttributeError("'NoneType' object has no attribute 'pick_files'")>
Traceback (most recent call last):
  File "D:\program\python\Lib\concurrent\futures\thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\workspace\code\plan\.venv\Lib\site-packages\flet_core\page.py", line 528, in wrapper      
    handler(*args)
  File "D:\workspace\code\plan\flet_study\demo.py", line 27, in pick_file_dialog
    file_picker.current.pick_files()
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'pick_files'

my question is: how to use custom control with ref?

(Optional): Suggest A Solution

(Replace This Text: A concise description of your preferred solution. Things to address include:

If there are multiple solutions, please present each one separately. Save comparisons for the very end.)