Skip to content
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

Fix parsing issues in TextStyle and *Event classes #3551

Merged
merged 4 commits into from
Jul 23, 2024
Merged
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
22 changes: 9 additions & 13 deletions packages/flet/lib/src/controls/create_control.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1218,15 +1218,14 @@ Widget _positionedControl(
}

Widget _sizedControl(Widget widget, Control? parent, Control control) {
var width = control.attrDouble("width", null);
var height = control.attrDouble("height", null);
if (width != null || height != null) {
if (control.type != "container" && control.type != "image") {
widget = ConstrainedBox(
constraints: BoxConstraints.tightFor(width: width, height: height),
child: widget,
);
}
var width = control.attrDouble("width");
var height = control.attrDouble("height");
if ((width != null || height != null) &&
!["container", "image"].contains(control.type)) {
widget = ConstrainedBox(
constraints: BoxConstraints.tightFor(width: width, height: height),
child: widget,
);
}
var animation = parseAnimation(control, "animateSize");
if (animation != null) {
Expand All @@ -1237,10 +1236,7 @@ Widget _sizedControl(Widget widget, Control? parent, Control control) {
}

Widget _expandable(Widget widget, Control? parent, Control control) {
if (parent != null &&
(parent.type == "view" ||
parent.type == "column" ||
parent.type == "row")) {
if (parent != null && ["view", "column", "row"].contains(parent.type)) {
int? expand = control.attrInt("expand");
var expandLoose = control.attrBool("expandLoose");
return expand != null
Expand Down
2 changes: 1 addition & 1 deletion packages/flet/lib/src/controls/textfield.dart
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ class _TextFieldControlState extends State<TextFieldControl>
}

TextCapitalization textCapitalization = parseTextCapitalization(
widget.control.attrString("textCapitalization"),
widget.control.attrString("capitalization"),
TextCapitalization.none)!;

FilteringTextInputFormatter? inputFilter =
Expand Down
22 changes: 5 additions & 17 deletions packages/flet/lib/src/utils/theme.dart
Original file line number Diff line number Diff line change
Expand Up @@ -948,7 +948,7 @@ PopupMenuThemeData? parsePopupMenuTheme(
iconColor: parseColor(theme, j["icon_color"]),
textStyle: parseTextStyle("text_style"),
labelTextStyle: getWidgetStateProperty<TextStyle?>(
j["label_text_style"], (jv) => parseTextStyle(jv)),
j["label_text_style"], (jv) => textStyleFromJson(theme, jv)),
enableFeedback: parseBool(j["enable_feedback"]),
elevation: parseDouble(j["elevation"]),
iconSize: parseDouble(j["icon_size"]),
Expand All @@ -968,10 +968,6 @@ SearchBarThemeData? parseSearchBarTheme(
return null;
}

TextStyle? parseTextStyle(String propName) {
return j[propName] != null ? textStyleFromJson(theme, j[propName]) : null;
}

return theme.searchBarTheme.copyWith(
surfaceTintColor: getWidgetStateProperty<Color?>(
j["surface_tint_color"], (jv) => parseColor(theme, jv as String)),
Expand All @@ -984,9 +980,9 @@ SearchBarThemeData? parseSearchBarTheme(
overlayColor: getWidgetStateProperty<Color?>(
j["overlay_color"], (jv) => parseColor(theme, jv as String)),
textStyle: getWidgetStateProperty<TextStyle?>(
j["text_style"], (jv) => parseTextStyle(jv)),
j["text_style"], (jv) => textStyleFromJson(theme, jv)),
hintStyle: getWidgetStateProperty<TextStyle?>(
j["hint_style"], (jv) => parseTextStyle(jv)),
j["hint_style"], (jv) => textStyleFromJson(theme, jv)),
shape: getWidgetStateProperty<OutlinedBorder?>(
j["shape"], (jv) => outlinedBorderFromJSON(jv)),
textCapitalization: j["text_capitalization"] != null
Expand Down Expand Up @@ -1051,10 +1047,6 @@ NavigationDrawerThemeData? parseNavigationDrawerTheme(
return null;
}

TextStyle? parseTextStyle(String propName) {
return j[propName] != null ? textStyleFromJson(theme, j[propName]) : null;
}

return theme.navigationDrawerTheme.copyWith(
backgroundColor: parseColor(theme, j["bgcolor"]),
shadowColor: parseColor(theme, j["shadow_color"]),
Expand All @@ -1064,7 +1056,7 @@ NavigationDrawerThemeData? parseNavigationDrawerTheme(
//indicatorSize: ,
tileHeight: parseDouble(j["tile_height"]),
labelTextStyle: getWidgetStateProperty<TextStyle?>(
j["label_text_style"], (jv) => parseTextStyle(jv)),
j["label_text_style"], (jv) => textStyleFromJson(theme, jv)),
indicatorShape: j["indicator_shape"] != null
? outlinedBorderFromJSON(j["indicator_shape"])
: null,
Expand All @@ -1077,10 +1069,6 @@ NavigationBarThemeData? parseNavigationBarTheme(
return null;
}

TextStyle? parseTextStyle(String propName) {
return j[propName] != null ? textStyleFromJson(theme, j[propName]) : null;
}

return theme.navigationBarTheme.copyWith(
backgroundColor: parseColor(theme, j["bgcolor"]),
shadowColor: parseColor(theme, j["shadow_color"]),
Expand All @@ -1091,7 +1079,7 @@ NavigationBarThemeData? parseNavigationBarTheme(
elevation: parseDouble(j["elevation"]),
height: parseDouble(j["height"]),
labelTextStyle: getWidgetStateProperty<TextStyle?>(
j["label_text_style"], (jv) => parseTextStyle(jv)),
j["label_text_style"], (jv) => textStyleFromJson(theme, jv)),
indicatorShape: j["indicator_shape"] != null
? outlinedBorderFromJSON(j["indicator_shape"])
: null,
Expand Down
12 changes: 6 additions & 6 deletions packages/flet_flashlight/lib/src/flashlight.dart
Original file line number Diff line number Diff line change
Expand Up @@ -30,22 +30,22 @@ class _FlashlightControlState extends State<FlashlightControl> {
if (Platform.isIOS || Platform.isAndroid) {
() async {
widget.backend.subscribeMethods(widget.control.id,
(meathodName, args) async {
switch (meathodName) {
(methodName, args) async {
switch (methodName) {
case "on":
try {
await TorchLight.enableTorch();
return "1";
} on Exception catch (_) {
debugPrint("Couldn't enable Flash: $_");
} on Exception catch (e) {
debugPrint("Couldn't enable Flash: $e");
return "0";
}
case "off":
try {
await TorchLight.disableTorch();
return "1";
} on Exception catch (_) {
debugPrint("Couldn't disable Flash");
} on Exception catch (e) {
debugPrint("Couldn't disable Flash: $e");
return "0";
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,5 +99,5 @@ def __init__(self, e: ControlEvent):
super().__init__(e.target, e.name, e.data, e.control, e.page)
d = json.loads(e.data)
self.selection: AutoCompleteSuggestion = AutoCompleteSuggestion(
key=d["key"], value=d["value"]
key=d.get("key"), value=d.get("value")
)
6 changes: 2 additions & 4 deletions sdk/python/packages/flet-core/src/flet_core/canvas/canvas.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import json
from dataclasses import dataclass
from typing import Any, List, Optional, Union, Callable

from flet_core.canvas.shape import Shape
Expand Down Expand Up @@ -151,10 +150,9 @@ def on_resize(self, handler: Optional[Callable[["CanvasResizeEvent"], None]]):
self._set_attr("onresize", True if handler is not None else None)


@dataclass
class CanvasResizeEvent(ControlEvent):
def __init__(self, e: ControlEvent) -> None:
super().__init__(e.target, e.name, e.data, e.control, e.page)
d = json.loads(e.data)
self.width: float = d["w"]
self.height: float = d["h"]
self.width: float = d.get("w")
self.height: float = d.get("h")
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ class BarChartEvent(ControlEvent):
def __init__(self, e: ControlEvent) -> None:
super().__init__(e.target, e.name, e.data, e.control, e.page)
d = json.loads(e.data)
self.type: str = d["type"]
self.group_index: int = d["group_index"]
self.rod_index: int = d["rod_index"]
self.stack_item_index: int = d["stack_item_index"]
self.type: str = d.get("type")
self.group_index: int = d.get("group_index")
self.rod_index: int = d.get("rod_index")
self.stack_item_index: int = d.get("stack_item_index")
Original file line number Diff line number Diff line change
Expand Up @@ -352,8 +352,8 @@ class LineChartEvent(ControlEvent):
def __init__(self, e: ControlEvent):
super().__init__(e.target, e.name, e.data, e.control, e.page)
d = json.loads(e.data)
self.type: str = d["type"]
self.spots: List[LineChartEventSpot] = d["spots"]
self.type: str = d.get("type")
self.spots: List[LineChartEventSpot] = d.get("spots")


class LineChartEventSpot:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ class PieChartEvent(ControlEvent):
def __init__(self, e: ControlEvent):
super().__init__(e.target, e.name, e.data, e.control, e.page)
d = json.loads(e.data)
self.type: str = d["type"]
self.section_index: int = d["section_index"]
# self.radius: float = d["radius"]
# self.angle: float = d["angle"]
self.type: str = d.get("type")
self.section_index: int = d.get("section_index")
# self.radius: float = d.get("radius")
# self.angle: float = d.get("angle")
8 changes: 4 additions & 4 deletions sdk/python/packages/flet-core/src/flet_core/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,7 @@ class ContainerTapEvent(ControlEvent):
def __init__(self, e: ControlEvent):
super().__init__(e.target, e.name, e.data, e.control, e.page)
d = json.loads(e.data)
self.local_x: float = d["lx"]
self.local_y: float = d["ly"]
self.global_x: float = d["gx"]
self.global_y: float = d["gy"]
self.local_x: float = d.get("lx")
self.local_y: float = d.get("ly")
self.global_x: float = d.get("gx")
self.global_y: float = d.get("gy")
4 changes: 2 additions & 2 deletions sdk/python/packages/flet-core/src/flet_core/datatable.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ class DataColumnSortEvent(ControlEvent):
def __init__(self, e: ControlEvent):
super().__init__(e.target, e.name, e.data, e.control, e.page)
d = json.loads(e.data)
self.column_index: int = d["i"]
self.ascending: bool = d["a"]
self.column_index: int = d.get("i")
self.ascending: bool = d.get("a")
Comment on lines +30 to +31
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Potential issue with default values in DataColumnSortEvent

Using d.get() without default values might cause issues if the keys are not present. Consider providing default values or handling None cases.



class DataColumn(Control):
Expand Down
10 changes: 5 additions & 5 deletions sdk/python/packages/flet-core/src/flet_core/dismissible.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,14 +293,14 @@ class DismissibleDismissEvent(ControlEvent):
def __init__(self, e: ControlEvent):
super().__init__(e.target, e.name, e.data, e.control, e.page)
d = json.loads(e.data)
self.direction = DismissDirection(d["direction"])
self.direction: DismissDirection = DismissDirection(d.get("direction"))


class DismissibleUpdateEvent(ControlEvent):
def __init__(self, e: ControlEvent):
super().__init__(e.target, e.name, e.data, e.control, e.page)
d = json.loads(e.data)
self.direction = DismissDirection(d["direction"])
self.progress = d["progress"]
self.reached = d["reached"]
self.previous_reached = d["previous_reached"]
self.direction: DismissDirection = DismissDirection(d.get("direction"))
self.progress: float = d.get("progress")
self.reached: bool = d.get("reached")
Comment on lines +296 to +305
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Potential issue with default values in DismissibleUpdateEvent

Using d.get() without default values might cause issues if the keys are not present. Consider providing default values or handling None cases.

self.previous_reached: bool = d.get("previous_reached")
12 changes: 6 additions & 6 deletions sdk/python/packages/flet-core/src/flet_core/drag_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,15 +215,15 @@ def __init__(self, e: ControlEvent):
category=DeprecationWarning,
stacklevel=2,
)
self.src_id: float = d["src_id"]
self.x: float = d["x"]
self.y: float = d["y"]
self.src_id: float = d.get("src_id")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider explicitly handling missing keys instead of using get.

The new code introduces additional complexity by using the get method for dictionary access, which can silently assign None to attributes if keys are missing. This can mask issues and make debugging harder. The original code's direct dictionary access would raise a KeyError, providing a clear signal when expected keys are missing. If handling missing keys is necessary, it should be done explicitly with proper error handling. Here's a suggested approach:

class DragTargetAcceptEvent(ControlEvent):
    def __init__(self, e: ControlEvent):
        super().__init__(e.target, e.name, e.data, e.control, e.page)
        d = json.loads(e.data)
        warn(
            f"{self.__class__.__name__} is deprecated since version 0.22.0 "
            f"and will be removed in version 0.26.0. Use DragTargetEvent instead.",
            category=DeprecationWarning,
            stacklevel=2,
        )
        try:
            self.src_id: float = d["src_id"]
            self.x: float = d["x"]
            self.y: float = d["y"]
        except KeyError as key_error:
            raise ValueError(f"Missing expected key in data: {key_error}")

class DragTargetEvent(ControlEvent):
    def __init__(self, e: ControlEvent):
        super().__init__(e.target, e.name, e.data, e.control, e.page)
        d = json.loads(e.data)
        try:
            self.src_id: float = d["src_id"]
            self.x: float = d["x"]
            self.y: float = d["y"]
        except KeyError as key_error:
            raise ValueError(f"Missing expected key in data: {key_error}")

This maintains simplicity while explicitly handling missing keys, making the code more robust and easier to maintain.

self.x: float = d.get("x")
self.y: float = d.get("y")


class DragTargetEvent(ControlEvent):
def __init__(self, e: ControlEvent):
super().__init__(e.target, e.name, e.data, e.control, e.page)
d = json.loads(e.data)
self.src_id: float = d["src_id"]
self.x: float = d["x"]
self.y: float = d["y"]
self.src_id: float = d.get("src_id")
self.x: float = d.get("x")
self.y: float = d.get("y")
11 changes: 5 additions & 6 deletions sdk/python/packages/flet-core/src/flet_core/file_picker.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,23 +48,22 @@ class FilePickerResultEvent(ControlEvent):
def __init__(self, e: ControlEvent):
super().__init__(e.target, e.name, e.data, e.control, e.page)
d = json.loads(e.data)
self.path: Optional[str] = d["path"]
self.path: Optional[str] = d.get("path")
self.files: Optional[List[FilePickerFile]] = None
files = d["files"]
files = d.get("files")
if files is not None and isinstance(files, List):
self.files = []
for fd in files:
self.files.append(FilePickerFile(**fd))


@dataclass
class FilePickerUploadEvent(ControlEvent):
def __init__(self, e: ControlEvent):
super().__init__(e.target, e.name, e.data, e.control, e.page)
d = json.loads(e.data)
self.file_name: str = d["file_name"]
self.progress: Optional[float] = d["progress"]
self.error: Optional[str] = d["error"]
self.file_name: str = d.get("file_name")
self.progress: Optional[float] = d.get("progress")
self.error: Optional[str] = d.get("error")


class FilePicker(Control):
Expand Down
Loading