Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .github/scripts/templates/cupertino_icons.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ from flet.controls.icon_data import IconData

__all__ = ["CupertinoIcons"]

class CupertinoIcons:
class _CupertinoIconsMeta(type):
def __getitem__(cls, name: str) -> IconData: ...
def __contains__(cls, item: object) -> bool: ...

class CupertinoIcons(metaclass=_CupertinoIconsMeta):
{% for name, code in icons -%}
{{ name.upper() }}: IconData
{% endfor -%}
6 changes: 5 additions & 1 deletion .github/scripts/templates/lucide_icons.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ from flet.controls.icon_data import IconData

__all__ = ["LucideIcons"]

class LucideIcons:
class _LucideIconsMeta(type):
def __getitem__(cls, name: str) -> IconData: ...
def __contains__(cls, item: object) -> bool: ...

class LucideIcons(metaclass=_LucideIconsMeta):
{% for name in icons -%}
{{ name }}: IconData
{% endfor -%}
6 changes: 5 additions & 1 deletion .github/scripts/templates/material_icons.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ from flet.controls.icon_data import IconData

__all__ = ["Icons"]

class Icons:
class _IconsMeta(type):
def __getitem__(cls, name: str) -> IconData: ...
def __contains__(cls, item: object) -> bool: ...

class Icons(metaclass=_IconsMeta):
{% for name, code in icons -%}
{{ name.upper() }}: IconData
{% endfor -%}
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@

### Improvements

* Look up icons by name, as with enum members: `ft.Icons["HOME"]`, `ft.CupertinoIcons["ADD"]` and `LucideIcons[...]`, and check a name with `"HOME" in ft.Icons` ([#7114](https://github.com/flet-dev/flet/pull/7114)) by @FeodorFitsner.
* `ft.use_dialog()` raises a `TypeError` for a dialog returned from an `@ft.component` function, or any other control that isn't a dialog, instead of silently never opening it ([#7114](https://github.com/flet-dev/flet/pull/7114)) by @FeodorFitsner.
* Start web apps that use `flet-rive` 1 MB lighter when they don't show a `Rive` control: the Rive engine (`rive_native.wasm`) now loads when the first `Rive` control loads its file, instead of at startup ([#7057](https://github.com/flet-dev/flet/pull/7057)) by @FeodorFitsner.

### Bug fixes

* Fix `ft.use_memo()` and `ft.use_effect()` ignoring in-place changes to an observable's list or dict passed as a dependency, such as `state.items.append(x)`: the value is now recomputed and the effect re-run ([#7114](https://github.com/flet-dev/flet/pull/7114)) by @FeodorFitsner.
* Fix SVG images drawing blank when their URL has a query string or fragment, such as a cache-busting `icon.svg?v=2`: `Image` now recognizes an SVG by the URL's path, in any letter case ([#7057](https://github.com/flet-dev/flet/pull/7057)) by @FeodorFitsner.
* Fix `Text` with `spans` ignoring `overflow`: a rich text cut off by `max_lines` now ends in an ellipsis with `overflow=TextOverflow.ELLIPSIS`, as plain text does, instead of being clipped at a word ([#7057](https://github.com/flet-dev/flet/pull/7057)) by @FeodorFitsner.
* Fix mypy inferring `type[Never]` for classes decorated with `@control("Name")`: the overload that takes arguments now accepts only a string `dart_widget_name` ([#7085](https://github.com/flet-dev/flet/issues/7085), [#7087](https://github.com/flet-dev/flet/pull/7087)) by @joaoaracheski.
Expand Down
2 changes: 1 addition & 1 deletion sdk/python/.pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,4 @@ repos:
# misspellings for typo-tolerant search; and the generated icon
# name lists carry Flutter's own spelling, including a handful of
# upstream misspellings we cannot correct without breaking the API.
exclude: (/templates/|\.pbxproj$|flet_mcp/data/icons\.json$|icon-codepoints\.json$|controls/material/icons\.json$|controls/cupertino/cupertino_icons\.json$|flet_shadcn_ui/lucide_icons\.(json|pyi)$|flet_shadcn_ui/lib/src/utils/lucide_icons\.dart$|lib/src/utils/(material|cupertino)_icons\.dart$)
exclude: (/templates/|\.pbxproj$|flet_mcp/data/icons\.json$|icon-codepoints\.json$|controls/material/icons\.(json|pyi)$|controls/cupertino/cupertino_icons\.(json|pyi)$|flet_shadcn_ui/lucide_icons\.(json|pyi)$|flet_shadcn_ui/lib/src/utils/lucide_icons\.dart$|lib/src/utils/(material|cupertino)_icons\.dart$)
2 changes: 2 additions & 0 deletions sdk/python/_typos.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ extend-exclude = [
"*icon-codepoints.json",
"*/controls/material/icons.json",
"*/controls/cupertino/cupertino_icons.json",
"*/controls/material/icons.pyi",
"*/controls/cupertino/cupertino_icons.pyi",
"packages/flet/lib/src/utils/material_icons.dart",
"packages/flet/lib/src/utils/cupertino_icons.dart",
# Generated from lucide_icons_flutter; keeps Lucide's legacy aliases such
Expand Down
6 changes: 6 additions & 0 deletions sdk/python/packages/flet-shadcn-ui/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## 1.1.3

### Added

- Look up Lucide icons by name, as with enum members: `LucideIcons["HOUSE"]`, and check a name with `"HOUSE" in LucideIcons` ([#7114](https://github.com/flet-dev/flet/pull/7114)) by @FeodorFitsner.

## 1.1.2

### Changed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,21 @@ def __getattr__(self, name: str) -> IconData:
except KeyError:
raise AttributeError(name) from None

def __getitem__(self, name: str) -> IconData:
"""Look up an icon by its name, such as `"HOME"`, like an enum member."""
try:
return self._get_member(name)
except KeyError:
raise KeyError(name) from None

def __contains__(self, item: object) -> bool:
"""`"HOME" in Icons` checks a name; `icon in Icons` checks an icon."""
if isinstance(item, str):
self._load()
assert self._map is not None
return item in self._map
return item in self._get_values()

def __dir__(self) -> list[str]:
self._load()
assert self._map is not None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ from flet.controls.icon_data import IconData

__all__ = ["LucideIcons"]

class LucideIcons:
class _LucideIconsMeta(type):
def __getitem__(cls, name: str) -> IconData: ...
def __contains__(cls, item: object) -> bool: ...

class LucideIcons(metaclass=_LucideIconsMeta):
A_ARROW_DOWN: IconData
A_ARROW_UP: IconData
A_LARGE_SMALL: IconData
Expand Down
25 changes: 25 additions & 0 deletions sdk/python/packages/flet/src/flet/components/hooks/use_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import dataclasses
import weakref

from flet.components.component import Component
from flet.components.hooks.use_effect import use_effect
from flet.components.hooks.use_ref import use_ref
from flet.controls.context import context
Expand Down Expand Up @@ -49,6 +50,23 @@ def _bind_dialog_subtree(value, parent):
_bind_dialog_subtree(item, parent)


def _not_a_dialog_message(value) -> str:
fn = getattr(value, "fn", None)
if isinstance(value, Component) and fn is not None:
name = getattr(fn, "__name__", "component")
return (
f"use_dialog() needs a dialog control such as ft.AlertDialog, "
f"got the component {name}(). A dialog returned from an "
f"@ft.component function can't be opened: build the dialog inline, "
f"or in a plain function without @ft.component, and pass it to "
f"use_dialog()."
)
return (
f"use_dialog() needs a dialog control such as ft.AlertDialog, "
f"ft.BottomSheet or ft.DatePicker, got {type(value).__name__}."
)


def use_dialog(dialog: DialogControl | None = None):
"""
Portal a :class:`~flet.DialogControl` to the page's dialog overlay.
Expand All @@ -64,7 +82,14 @@ def use_dialog(dialog: DialogControl | None = None):
Args:
dialog: A :class:`~flet.DialogControl` to display, or `None`
to hide it.

Raises:
TypeError: If `dialog` is not a :class:`~flet.DialogControl`, such as
a dialog returned from a :func:`~flet.component` function.
"""
if dialog is not None and not isinstance(dialog, DialogControl):
raise TypeError(_not_a_dialog_message(dialog))

ref = use_ref(None)
page = context.page

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from typing import Any

from flet.components.hooks.hook import Hook
from flet.components.observable import capture_dependencies
from flet.components.utils import current_component


Expand Down Expand Up @@ -147,7 +148,9 @@ def use_effect(
dependencies: Values the effect depends on. The effect always runs after the
component mounts. If absent, it also re-runs after every render. If
empty, it runs only on mount. Otherwise, it re-runs only when one of the
dependencies has changed.
dependencies has changed. A list or dict field of an
:func:`~flet.observable` counts as changed when it is changed in place,
such as by `items.append(x)`.
cleanup: A function that cleans up after the effect, run after the cleanup
the setup returned. It may be `async`.

Expand Down Expand Up @@ -177,7 +180,7 @@ async def tick():
```
"""
component = current_component()
deps = list(dependencies) if dependencies is not None else None
deps = capture_dependencies(dependencies) if dependencies is not None else None

# get or create effect hook
hook = component.use_hook(
Expand Down
10 changes: 7 additions & 3 deletions sdk/python/packages/flet/src/flet/components/hooks/use_memo.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from typing import Any, Callable, Generic, TypeVar

from flet.components.hooks.hook import Hook
from flet.components.observable import capture_dependencies
from flet.components.utils import current_component, shallow_compare_args

MemoValueT = TypeVar("MemoValueT")
Expand Down Expand Up @@ -33,7 +34,9 @@ def use_memo(
dependencies: Values the computation depends on. If absent, the value is
recomputed on every render. If empty, it is computed only on the first
render. Otherwise, it is recomputed only when one of the dependencies
has changed.
has changed. A list or dict field of an :func:`~flet.observable`
counts as changed when it is changed in place, such as by
`items.append(x)`.

Returns:
The memoized value. The same object is returned on every render until the
Expand Down Expand Up @@ -61,8 +64,9 @@ def _create() -> MemoHook[MemoValueT]:
hook.value = calculate_value()
return hook.value # type: ignore[return-value]

if hook.prev_deps is None or not shallow_compare_args(hook.prev_deps, dependencies):
deps = capture_dependencies(dependencies)
if hook.prev_deps is None or not shallow_compare_args(hook.prev_deps, deps):
hook.value = calculate_value()
hook.prev_deps = list(dependencies)
hook.prev_deps = deps

return hook.value # type: ignore[return-value]
77 changes: 77 additions & 0 deletions sdk/python/packages/flet/src/flet/components/observable.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import numbers
import threading
import weakref
from collections.abc import Sequence
from dataclasses import InitVar, dataclass
from typing import TYPE_CHECKING, Any, Callable, Optional

Expand Down Expand Up @@ -191,9 +192,33 @@ def _notify(self, field: str | None):
"""

self.__version__ += 1
versions = self.__field_versions
versions[field] = versions.get(field, 0) + 1
for fn in list(self.__listeners):
fn(self, field)

@property
def __field_versions(self) -> dict[str | None, int]:
"""
Lazily initialized change counters by field name (`None` for `notify()`).
"""

storage_name = "_Observable__field_versions_storage"
try:
return object.__getattribute__(self, storage_name)
except AttributeError:
versions: dict[str | None, int] = {}
object.__setattr__(self, storage_name, versions)
return versions

def _field_version(self, field: str) -> tuple[int, int]:
"""
Change counters of a field: its own and the one `notify()` bumps.
"""

versions = self.__field_versions
return versions.get(field, 0), versions.get(None, 0)

def notify(self):
"""
Manually notify listeners that something changed.
Expand Down Expand Up @@ -328,6 +353,15 @@ def _touch(self):
if owner:
owner._notify(self._field)

def _version(self) -> Any:
"""
A value that changes whenever this collection, or a collection nested in
it, changes in place.
"""

owner = self._owner_ref()
return owner._field_version(self._field) if owner else None

def _wrapper(self) -> Callable[[Any], Any]:
"""
Return a function that wraps values before they are stored.
Expand Down Expand Up @@ -654,3 +688,46 @@ def setdefault(self, k, d=None):
super().__setitem__(k, self._wrap(d))
self._touch()
return dict.__getitem__(self, k)


# Hook dependencies ---------------------------------------------


class _CollectionDependency:
"""
An observable collection in a hook's dependencies, with its version when the
dependencies were captured.

The same collection is unchanged only while its version stays the same, so
`use_memo` and `use_effect` see in-place changes such as `items.append(x)`.
Different collections compare by their items, as plain lists and dicts do.
"""

__slots__ = ("collection", "version")

def __init__(self, collection: _ObservableCollection):
self.collection = collection
self.version = collection._version()

def __eq__(self, other: object) -> bool:
if not isinstance(other, _CollectionDependency):
return NotImplemented
if self.collection is other.collection:
return self.version == other.version
return self.collection == other.collection

__hash__ = None # type: ignore[assignment]


def capture_dependencies(dependencies: Sequence[Any]) -> list[Any]:
"""
Snapshot hook dependencies for comparison on the next render.

Observable lists and dicts are recorded with their version, since they stay
the same object when they change in place.
"""

return [
_CollectionDependency(d) if isinstance(d, _ObservableCollection) else d
for d in dependencies
]
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,21 @@ def __getattr__(self, name: str) -> IconData:
except KeyError:
raise AttributeError(name) from None

def __getitem__(self, name: str) -> IconData:
"""Look up an icon by its name, such as `"HOME"`, like an enum member."""
try:
return self._get_member(name)
except KeyError:
raise KeyError(name) from None

def __contains__(self, item: object) -> bool:
"""`"HOME" in Icons` checks a name; `icon in Icons` checks an icon."""
if isinstance(item, str):
self._load()
assert self._map is not None
return item in self._map
return item in self._get_values()

def __dir__(self) -> list[str]:
self._load()
assert self._map is not None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ from flet.controls.icon_data import IconData

__all__ = ["CupertinoIcons"]

class CupertinoIcons:
class _CupertinoIconsMeta(type):
def __getitem__(cls, name: str) -> IconData: ...
def __contains__(cls, item: object) -> bool: ...

class CupertinoIcons(metaclass=_CupertinoIconsMeta):
ADD: IconData
ADD_CIRCLED: IconData
ADD_CIRCLED_SOLID: IconData
Expand Down
15 changes: 15 additions & 0 deletions sdk/python/packages/flet/src/flet/controls/material/icons.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,21 @@ def __getattr__(self, name: str) -> IconData:
except KeyError:
raise AttributeError(name) from None

def __getitem__(self, name: str) -> IconData:
"""Look up an icon by its name, such as `"HOME"`, like an enum member."""
try:
return self._get_member(name)
except KeyError:
raise KeyError(name) from None

def __contains__(self, item: object) -> bool:
"""`"HOME" in Icons` checks a name; `icon in Icons` checks an icon."""
if isinstance(item, str):
self._load()
assert self._map is not None
return item in self._map
return item in self._get_values()

def __dir__(self) -> list[str]:
self._load()
assert self._map is not None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ from flet.controls.icon_data import IconData

__all__ = ["Icons"]

class Icons:
class _IconsMeta(type):
def __getitem__(cls, name: str) -> IconData: ...
def __contains__(cls, item: object) -> bool: ...

class Icons(metaclass=_IconsMeta):
ABC: IconData
ABC_OUTLINED: IconData
ABC_ROUNDED: IconData
Expand Down
Loading
Loading