Skip to content

Update Ref to support initialization and assign optional value #5325

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 11, 2025

Conversation

yantaozhao
Copy link

@yantaozhao yantaozhao commented May 22, 2025

Description

Support initialize Ref with value directly, and allow re-assign None for intent clarify if needed.

Example code

In some scenarios, one control was created without known ref or the ref unavailable, but will be referenced in future.
It is more concise to direct initialize a ref with value rather than in a separate assignment statement.

# factory method to create and return a flet control
def control_factory(control_type: str) -> ft.Control:
    match control_type:
        case pattern_1:
            return ft.TextField(...)  # no ref here
        case pattern_2:
            return ft.Switch(...)
        case pattern_3:
            return ft.Slider(...)
        case ...:
            ......

controls: list[ft.Ref] = []  # list of ref to use later
control: ft.Control = control_factory(...)  # <-- create control in factory, with no ref passing into factory
# control_ref = ft.Ref()
# control_ref.current = control
control_ref = ft.Ref(control)  # <-- initialize directly instead of passing ref variable into factory or assigning it in another statement
controls.append(control_ref)

......
controls[i].current = None  # <-- later, no need to ref to control, but keep ref itself for some reason

Type of change

  • Bug fix: TypeError: cannot create weak reference to 'NoneType' object when passing None to setter.
  • New feature: initialize Ref

Summary by Sourcery

Enable direct Ref initialization with a value and optional None assignment to explicitly clear the reference

New Features:

  • Allow initializing Ref with an optional initial value via constructor
  • Enable clearing a Ref by assigning None to its current property

@ndonkoHenri
Copy link
Contributor

Thanks for your contribution. Will be reviewed when possible.

@ndonkoHenri ndonkoHenri requested a review from FeodorFitsner June 2, 2025 02:12
@FeodorFitsner FeodorFitsner merged commit 0fad639 into flet-dev:v1 Jun 11, 2025
1 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants