pyflutter-ui 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1283 @@
1
+ # widgets.py
2
+ from __future__ import annotations
3
+ from enum import Enum
4
+ import tkinter as tk
5
+ from tkinter import ttk
6
+ from typing import Optional, Callable, cast, Any, Literal
7
+
8
+ from pyflutter_ui.ui.core import (
9
+ BuildContext,
10
+ Element,
11
+ FlutterWidget,
12
+ GlobalKey,
13
+ StatelessWidget,
14
+ BaseMaterialApp,
15
+ RenderObject,
16
+ inflate_widget,
17
+ PageApp,
18
+ )
19
+ from pyflutter_ui.ui.container import Container, SizedBox
20
+ from pyflutter_ui.navigator import NavigatorApp, Navigator
21
+ from pyflutter_ui.scheduler import MainThreadScheduler
22
+
23
+
24
+ class TkMaterialApp(BaseMaterialApp):
25
+
26
+ def __init__(
27
+ self,
28
+ home: PageApp,
29
+ *,
30
+ theme: Any = None,
31
+ height: int = 350,
32
+ width: int = 480,
33
+ ) -> None:
34
+ super().__init__(home, theme)
35
+ self._navigator = NavigatorApp(self)
36
+ self._width: int = width
37
+ self._height: int = height
38
+ self._root: tk.Tk = tk.Tk()
39
+
40
+ @property
41
+ def geometry(self) -> str:
42
+ return f"{self._width}x{self._height}"
43
+
44
+ def set_height(self, new: int):
45
+ self._height = new
46
+ self.update_geometry()
47
+
48
+ def set_width(self, new: int):
49
+ self._width = new
50
+ self.update_geometry()
51
+
52
+ def update_geometry(self):
53
+ self.get_root().geometry(self.geometry)
54
+
55
+ def get_navigator(self) -> Navigator:
56
+ return self._navigator
57
+
58
+ def run(self) -> None:
59
+ if self._root is None:
60
+ self._root = tk.Tk()
61
+
62
+ self.update_geometry()
63
+ # self._root.title(self.home.name)
64
+
65
+ ##
66
+ MainThreadScheduler.attach(self.get_root())
67
+ ##
68
+ self.get_navigator().push(self.home)
69
+
70
+ try:
71
+ self._root.mainloop()
72
+ finally:
73
+ MainThreadScheduler.detach()
74
+
75
+
76
+ # ============================================================
77
+ # ALIGNMENTS
78
+ # ============================================================
79
+ class MainAxisAlignment(Enum):
80
+ START = "start"
81
+ CENTER = "center"
82
+ END = "end"
83
+ SPACE_BETWEEN = "space_between"
84
+ SPACE_AROUND = "space_around"
85
+ SPACE_EVENLY = "space_evenly"
86
+
87
+
88
+ class CrossAxisAlignment(Enum):
89
+ START = "start"
90
+ CENTER = "center"
91
+ END = "end"
92
+ STRETCH = "stretch"
93
+
94
+
95
+ class Alignment(Enum):
96
+ TOP_LEFT = "top_left"
97
+ TOP_CENTER = "top_center"
98
+ TOP_RIGHT = "top_right"
99
+
100
+ CENTER_LEFT = "center_left"
101
+ CENTER = "center"
102
+ CENTER_RIGHT = "center_right"
103
+
104
+ BOTTOM_LEFT = "bottom_left"
105
+ BOTTOM_CENTER = "bottom_center"
106
+ BOTTOM_RIGHT = "bottom_right"
107
+
108
+
109
+ class FlexRenderObject(RenderObject):
110
+
111
+ def __init__(
112
+ self,
113
+ direction: Literal["row", "column"],
114
+ *,
115
+ main_axis_alignment: MainAxisAlignment = MainAxisAlignment.CENTER,
116
+ cross_axis_alignment: CrossAxisAlignment = CrossAxisAlignment.CENTER,
117
+ ) -> None:
118
+ super().__init__()
119
+ self.direction = direction
120
+ self.main_axis_alignment: MainAxisAlignment = main_axis_alignment
121
+ self.cross_axis_alignment: CrossAxisAlignment = cross_axis_alignment
122
+
123
+ def apply_layout(self) -> None:
124
+ if self.tk_widget is None:
125
+ return
126
+
127
+ if self.direction == "row":
128
+ self.tk_widget.grid_rowconfigure(0, weight=1)
129
+ else:
130
+ self.tk_widget.grid_columnconfigure(0, weight=1)
131
+
132
+ # Calcula o anchor/sticky base para o cross axis
133
+ if self.direction == "row":
134
+ # ancora o filho à esquerda da célula quando main_axis é START
135
+ main_sticky = {
136
+ MainAxisAlignment.START: "w",
137
+ MainAxisAlignment.END: "e",
138
+ MainAxisAlignment.CENTER: "",
139
+ }.get(self.main_axis_alignment, "w")
140
+
141
+ cross_sticky = {
142
+ CrossAxisAlignment.START: "n",
143
+ CrossAxisAlignment.END: "s",
144
+ CrossAxisAlignment.CENTER: "",
145
+ CrossAxisAlignment.STRETCH: "ns",
146
+ }.get(self.cross_axis_alignment, "")
147
+ else:
148
+ main_sticky = {
149
+ MainAxisAlignment.START: "n",
150
+ MainAxisAlignment.END: "s",
151
+ MainAxisAlignment.CENTER: "",
152
+ }.get(self.main_axis_alignment, "n")
153
+
154
+ cross_sticky = {
155
+ CrossAxisAlignment.START: "w",
156
+ CrossAxisAlignment.END: "e",
157
+ CrossAxisAlignment.CENTER: "",
158
+ CrossAxisAlignment.STRETCH: "ew",
159
+ }.get(self.cross_axis_alignment, "")
160
+
161
+ for index, child in enumerate(self.children):
162
+ widget = child.tk_widget
163
+ if widget is None:
164
+ continue
165
+
166
+ flex = child.layout_data.flex
167
+ expand = child.layout_data.expand
168
+ fill_x = child.layout_data.fill_x
169
+ fill_y = child.layout_data.fill_y
170
+
171
+ if expand:
172
+ sticky = "nsew"
173
+ else:
174
+ # combina main + cross axis
175
+ sticky = main_sticky + cross_sticky
176
+ if fill_x:
177
+ sticky += "ew"
178
+ if fill_y:
179
+ sticky += "ns"
180
+
181
+ if self.direction == "row":
182
+ col_weight = flex if flex > 0 else 0
183
+ self.tk_widget.grid_columnconfigure(index, weight=col_weight)
184
+ widget.grid(row=0, column=index, sticky=sticky, padx=(0, 2))
185
+ else:
186
+ row_weight = flex if flex > 0 else 0
187
+ self.tk_widget.grid_rowconfigure(index, weight=row_weight)
188
+ widget.grid(row=index, column=0, sticky=sticky, pady=(0, 2))
189
+
190
+ def apply_layout_old(self) -> None:
191
+
192
+ if self.tk_widget is None:
193
+ return
194
+
195
+ # Row()
196
+ if self.direction == "row":
197
+ self.tk_widget.grid_rowconfigure(0, weight=1)
198
+ else:
199
+ # Column()
200
+ self.tk_widget.grid_columnconfigure(0, weight=1)
201
+
202
+ for index, child in enumerate(self.children):
203
+
204
+ widget = child.tk_widget
205
+ if widget is None:
206
+ continue
207
+
208
+ flex = child.layout_data.flex
209
+
210
+ expand = child.layout_data.expand
211
+
212
+ fill_x = child.layout_data.fill_x
213
+
214
+ fill_y = child.layout_data.fill_y
215
+
216
+ sticky = ""
217
+
218
+ if expand:
219
+ sticky = "nsew"
220
+ else:
221
+
222
+ if fill_x:
223
+ sticky += "ew"
224
+
225
+ if fill_y:
226
+ sticky += "ns"
227
+
228
+ weight = max(1, flex)
229
+
230
+ if self.direction == "row":
231
+ self.tk_widget.grid_columnconfigure(index, weight=weight)
232
+ widget.grid(row=0, column=index, sticky=sticky)
233
+ else:
234
+ self.tk_widget.grid_rowconfigure(index, weight=weight)
235
+ widget.grid(row=index, column=0, sticky=sticky)
236
+
237
+
238
+ # ============================================================
239
+ # TEXT
240
+ # ============================================================
241
+
242
+
243
+ class Text(StatelessWidget):
244
+
245
+ def __init__(self, text: str, key: GlobalKey | None = None) -> None:
246
+ super().__init__(key)
247
+ self.text: str = text
248
+
249
+ def build(self, context: BuildContext) -> FlutterWidget:
250
+ return self
251
+
252
+ def create_element(self) -> Element:
253
+ return TextElement(self)
254
+
255
+
256
+ class TextElement(Element[Text, ttk.Label]):
257
+
258
+ def __init__(self, widget: Text) -> None:
259
+ super().__init__(widget)
260
+
261
+ def get_widget_flutter(self) -> Text:
262
+ return self.widget_flutter
263
+
264
+ def mount(self, context: BuildContext) -> ttk.Label:
265
+ super().mount(context)
266
+
267
+ label = ttk.Label(context.parent_tk_widget, text=self.get_widget_flutter().text)
268
+ label.pack()
269
+ self.widget_tk = label
270
+ return label
271
+
272
+ def update(self, new_widget: FlutterWidget) -> None:
273
+ self.widget_flutter = cast(Text, new_widget)
274
+
275
+ if self.widget_tk is not None:
276
+ self.widget_tk.configure(text=self.widget_flutter.text)
277
+
278
+
279
+ # ============================================================
280
+ # PADDING
281
+ # ============================================================
282
+
283
+
284
+ class Padding(StatelessWidget):
285
+
286
+ def __init__(
287
+ self, key: GlobalKey | None = None, *, padding: int, child: FlutterWidget
288
+ ) -> None:
289
+ super().__init__(key)
290
+ self.padding = padding
291
+ self.child = child
292
+
293
+ def build(self, context: BuildContext) -> Padding:
294
+ return self
295
+
296
+ def create_element(self) -> PaddingElement:
297
+ return PaddingElement(self)
298
+
299
+
300
+ class PaddingElement(Element[Padding, ttk.Frame]):
301
+
302
+ def __init__(self, widget: Padding) -> None:
303
+ super().__init__(widget)
304
+
305
+ def update(self, new_widget: FlutterWidget) -> None:
306
+ context = self.get_context() # salva ANTES de trocar o widget
307
+ self.widget_flutter = cast(Padding, new_widget)
308
+ self.widget_flutter.context = context
309
+ if context:
310
+ self.unmount()
311
+ self.mount(context)
312
+
313
+ def get_widget_flutter(self) -> Padding:
314
+ return self.widget_flutter
315
+
316
+ def mount(self, context: BuildContext) -> ttk.Frame:
317
+ super().mount(context)
318
+ frame = ttk.Frame(context.parent_tk_widget)
319
+ frame.pack(
320
+ padx=self.get_widget_flutter().padding,
321
+ pady=self.get_widget_flutter().padding,
322
+ )
323
+ child_element = self.get_widget_flutter().child.create_element()
324
+
325
+ child_context = BuildContext(
326
+ app=context.app, parent_widget=frame, parent_context=context
327
+ )
328
+
329
+ child_element.mount(child_context)
330
+ self.widget_tk = frame
331
+ return frame
332
+
333
+
334
+ # ============================================================
335
+ # CENTER
336
+ # ============================================================
337
+
338
+
339
+ class Center(StatelessWidget):
340
+
341
+ def __init__(self, child: FlutterWidget, *, key: GlobalKey | None = None) -> None:
342
+ super().__init__(key)
343
+
344
+ self.child = child
345
+
346
+ def build(self, context: BuildContext) -> Center:
347
+ return self
348
+
349
+ def create_element(self) -> CenterElement:
350
+ return CenterElement(self)
351
+
352
+
353
+ class CenterElement(Element[Center, ttk.Frame]):
354
+
355
+ def __init__(self, widget: Center) -> None:
356
+ super().__init__(widget)
357
+
358
+ def get_widget_flutter(self) -> Center:
359
+ return self.widget_flutter
360
+
361
+ def mount(self, context: BuildContext) -> ttk.Frame:
362
+ super().mount(context)
363
+ frame = ttk.Frame(context.parent_tk_widget)
364
+ frame.pack(expand=True)
365
+ child_element = self.get_widget_flutter().child.create_element()
366
+
367
+ child_context = BuildContext(
368
+ app=context.app, parent_widget=frame, parent_context=context
369
+ )
370
+
371
+ child_element.mount(child_context)
372
+ self.widget_tk = frame
373
+ return frame
374
+
375
+
376
+ # ============================================================
377
+ # ALIGN
378
+ # ============================================================
379
+
380
+
381
+ class Align(StatelessWidget):
382
+
383
+ def __init__(
384
+ self,
385
+ child: FlutterWidget,
386
+ alignment: Alignment = (Alignment.CENTER),
387
+ *,
388
+ key: GlobalKey | None = None,
389
+ ) -> None:
390
+ super().__init__(key)
391
+
392
+ self.child = child
393
+ self.alignment = alignment
394
+
395
+ def build(self, context: BuildContext) -> FlutterWidget:
396
+ return self
397
+
398
+ def create_element(self) -> Element:
399
+ return AlignElement(self)
400
+
401
+
402
+ class AlignElement(Element[Align, ttk.Frame]):
403
+
404
+ def __init__(self, widget: Align) -> None:
405
+ super().__init__(widget)
406
+
407
+ def get_widget_flutter(self) -> Align:
408
+ return self.widget_flutter
409
+
410
+ def get_widget_tk(self) -> ttk.Frame:
411
+ return super().get_widget_tk()
412
+
413
+ def mount(self, context: BuildContext) -> ttk.Frame:
414
+ super().mount(context)
415
+ frame = ttk.Frame(context.parent_tk_widget)
416
+
417
+ anchor = {
418
+ Alignment.TOP_LEFT: "nw",
419
+ Alignment.TOP_CENTER: "n",
420
+ Alignment.TOP_RIGHT: "ne",
421
+ Alignment.CENTER_LEFT: "w",
422
+ Alignment.CENTER: "center",
423
+ Alignment.CENTER_RIGHT: "e",
424
+ Alignment.BOTTOM_LEFT: "sw",
425
+ Alignment.BOTTOM_CENTER: "s",
426
+ Alignment.BOTTOM_RIGHT: "se",
427
+ }.get(self.get_widget_flutter().alignment, "center")
428
+
429
+ frame.pack(fill="both", expand=True)
430
+
431
+ child_element = self.get_widget_flutter().child.create_element()
432
+ child_context = context.create_child_context(frame)
433
+ child_element.mount(child_context)
434
+
435
+ # ancora o filho dentro do frame
436
+ if child_element.widget_tk is not None:
437
+ child_element.widget_tk.pack_configure(anchor=anchor, expand=False)
438
+
439
+ self.widget_tk = frame
440
+ return frame
441
+
442
+
443
+ # ============================================================
444
+ # DIVIDER
445
+ # ============================================================
446
+
447
+
448
+ class Divider(StatelessWidget):
449
+
450
+ def __init__(
451
+ self,
452
+ *,
453
+ orientation: Literal["horizontal", "vertical"] = "horizontal",
454
+ key: GlobalKey | None = None,
455
+ ) -> None:
456
+ super().__init__(key)
457
+
458
+ self.orientation: Literal["horizontal", "vertical"] = orientation
459
+
460
+ def create_element(self) -> Element:
461
+ return DividerElement(self)
462
+
463
+ def build(self, context: BuildContext) -> FlutterWidget:
464
+ return self
465
+
466
+
467
+ class DividerElement(Element[Divider, ttk.Separator]):
468
+
469
+ def __init__(self, widget: Divider) -> None:
470
+ super().__init__(widget)
471
+
472
+ def get_widget_flutter(self) -> Divider:
473
+ return self.widget_flutter
474
+
475
+ def mount(self, context: BuildContext) -> ttk.Separator:
476
+ super().mount(context)
477
+ separator = ttk.Separator(
478
+ context.parent_tk_widget, orient=self.get_widget_flutter().orientation
479
+ )
480
+
481
+ if self.get_widget_flutter().orientation == "horizontal":
482
+ separator.pack(fill="x", padx=4)
483
+ elif self.get_widget_flutter().orientation == "vertical":
484
+ separator.pack(fill="y", pady=4)
485
+
486
+ self.widget_tk = separator
487
+ return separator
488
+
489
+
490
+ # ============================================================
491
+ # CARD
492
+ # ============================================================
493
+
494
+
495
+ class Card(Container):
496
+
497
+ def __init__(
498
+ self,
499
+ child: FlutterWidget | None = None,
500
+ width: int | None = None,
501
+ height: int | None = None,
502
+ padding: int = 0,
503
+ *,
504
+ key: GlobalKey | None = None,
505
+ ) -> None:
506
+ super().__init__(child, width, height, padding, key=key)
507
+
508
+
509
+ # ============================================================
510
+ # LIST ORIENTATION WIDGETS (super classe de Row e Column)
511
+ # ============================================================
512
+
513
+
514
+ class ListOrientationWidgets(StatelessWidget):
515
+ """
516
+ Base comum para widgets de lista com orientação fixa (Row/Column).
517
+ Centraliza toda a lógica de montagem, layout via FlexRenderObject e
518
+ atualização (update) em um único lugar — bugs corrigidos aqui valem
519
+ automaticamente para Row e Column.
520
+ """
521
+
522
+ def __init__(
523
+ self,
524
+ children: list[FlutterWidget],
525
+ direction: Literal["row", "column"],
526
+ main_axis_alignment: MainAxisAlignment = MainAxisAlignment.START,
527
+ cross_axis_alignment: CrossAxisAlignment = CrossAxisAlignment.CENTER,
528
+ *,
529
+ key: GlobalKey | None = None,
530
+ ) -> None:
531
+ super().__init__(key)
532
+
533
+ self.children: list[FlutterWidget] = children
534
+ self.direction: Literal["row", "column"] = direction
535
+ self.main_axis_alignment = main_axis_alignment
536
+ self.cross_axis_alignment = cross_axis_alignment
537
+
538
+ def build(self, context: BuildContext) -> "ListOrientationWidgets":
539
+ return self
540
+
541
+ def create_element(self) -> ListOrientationWidgetsElement:
542
+ return ListOrientationWidgetsElement(self)
543
+
544
+
545
+ class ListOrientationWidgetsElement(Element[ListOrientationWidgets, ttk.Frame]):
546
+
547
+ def __init__(self, widget: ListOrientationWidgets) -> None:
548
+ super().__init__(widget)
549
+ self._child_elements: list[Element] = []
550
+
551
+ self.render_object = FlexRenderObject(
552
+ direction=widget.direction,
553
+ main_axis_alignment=widget.main_axis_alignment,
554
+ cross_axis_alignment=widget.cross_axis_alignment,
555
+ )
556
+
557
+ def get_widget_flutter(self) -> ListOrientationWidgets:
558
+ return self.widget_flutter
559
+
560
+ def get_widget_tk(self) -> ttk.Frame:
561
+ return super().get_widget_tk()
562
+
563
+ def _pack_frame(self, frame: ttk.Frame) -> None:
564
+ """
565
+ Empacotamento do frame principal. Comportamento padrão = Column
566
+ (ocupa todo o espaço disponível). Subclasses (ex: RowElement)
567
+ sobrescrevem quando precisam de outro comportamento de packing.
568
+ """
569
+ frame.pack(fill="both", expand=True)
570
+
571
+ def update(self, new_widget: FlutterWidget) -> None:
572
+ # IMPORTANTE: usa get_context() (== widget_flutter.context), nunca
573
+ # um atributo tipo "_parent_context" guardado manualmente.
574
+ # Element.mount() sempre seta widget_flutter.context em TODA
575
+ # subclasse (é feito na base), então esta fonte nunca fica
576
+ # desatualizada — foi exatamente a falta disso que causava o bug
577
+ # de "monta certo na primeira vez, mas nunca atualiza depois".
578
+
579
+ context: BuildContext | None = self.get_context()
580
+
581
+ if context:
582
+ new_widget.context = context
583
+ self.widget_flutter = new_widget
584
+
585
+ self.render_object = FlexRenderObject(
586
+ direction=self.get_widget_flutter().direction,
587
+ main_axis_alignment=self.get_widget_flutter().main_axis_alignment,
588
+ cross_axis_alignment=self.get_widget_flutter().cross_axis_alignment,
589
+ )
590
+ self.unmount()
591
+ self.mount(context)
592
+
593
+ def mount(self, context: BuildContext) -> ttk.Frame:
594
+ super().mount(context)
595
+
596
+ if not context.parent_tk_widget.winfo_exists():
597
+ return None # pai já destruído, aborta silenciosamente em vez de TclError
598
+
599
+ frame = ttk.Frame(context.parent_tk_widget)
600
+ self._pack_frame(frame)
601
+ self.render_object.attach_widget(frame)
602
+
603
+ self._child_elements: list[Element] = []
604
+
605
+ for child in self.get_widget_flutter().children:
606
+ # wrapper entra no frame via grid (apply_layout faz isso)
607
+ # NÃO chamar pack/grid aqui no wrapper
608
+ wrapper = ttk.Frame(frame)
609
+
610
+ child_element: Element = inflate_widget(child)
611
+ child_context: BuildContext = context.create_child_context(wrapper)
612
+ child_element.mount(child_context)
613
+ self._child_elements.append(child_element)
614
+
615
+ render_object = child_element.render_object
616
+ render_object.attach_widget(wrapper)
617
+ self.render_object.add_child(render_object)
618
+
619
+ self.render_object.apply_layout()
620
+ self.widget_tk = frame
621
+ return frame
622
+
623
+ def unmount(self) -> None:
624
+ for child_element in self._child_elements:
625
+ child_element.unmount()
626
+ self._child_elements = []
627
+ super().unmount()
628
+
629
+
630
+ # ============================================================
631
+ # ROW
632
+ # ============================================================
633
+ class Row(ListOrientationWidgets):
634
+
635
+ def __init__(
636
+ self,
637
+ children: list[FlutterWidget],
638
+ main_axis_alignment: MainAxisAlignment = MainAxisAlignment.START,
639
+ cross_axis_alignment: CrossAxisAlignment = CrossAxisAlignment.CENTER,
640
+ *,
641
+ key: GlobalKey | None = None,
642
+ ) -> None:
643
+ super().__init__(
644
+ children, "row", main_axis_alignment, cross_axis_alignment, key=key
645
+ )
646
+
647
+ def create_element(self) -> RowElement:
648
+ return RowElement(self)
649
+
650
+
651
+ class RowElement(ListOrientationWidgetsElement):
652
+
653
+ def __init__(self, widget: ListOrientationWidgets) -> None:
654
+ super().__init__(widget)
655
+
656
+ def _pack_frame(self, frame: ttk.Frame) -> None:
657
+ frame.pack(fill="x", expand=False, padx=1, pady=1)
658
+
659
+
660
+ # ============================================================
661
+ # COLUMN
662
+ # ============================================================
663
+ class Column(ListOrientationWidgets):
664
+
665
+ def __init__(
666
+ self,
667
+ children: list[FlutterWidget],
668
+ main_axis_alignment: MainAxisAlignment = MainAxisAlignment.START,
669
+ cross_axis_alignment: CrossAxisAlignment = CrossAxisAlignment.CENTER,
670
+ *,
671
+ key: GlobalKey | None = None,
672
+ ) -> None:
673
+ super().__init__(
674
+ children, "column", main_axis_alignment, cross_axis_alignment, key=key
675
+ )
676
+
677
+ def create_element(self) -> "ColumnElement":
678
+ return ColumnElement(self)
679
+
680
+
681
+ class ColumnElement(ListOrientationWidgetsElement):
682
+
683
+ def __init__(self, widget: ListOrientationWidgets) -> None:
684
+ super().__init__(widget)
685
+
686
+
687
+ # ============================================================
688
+ # TEXT FIELD
689
+ # ============================================================
690
+
691
+
692
+ class TextField(StatelessWidget):
693
+
694
+ def __init__(
695
+ self,
696
+ text: str = "",
697
+ hint: str = "",
698
+ on_changed: Callable[[str], None] | None = None,
699
+ width: int = 30,
700
+ *,
701
+ key: GlobalKey | None = None,
702
+ ) -> None:
703
+ super().__init__(key)
704
+
705
+ self.text = text
706
+ self.hint = hint
707
+ self.on_changed = on_changed
708
+ self.width = width
709
+
710
+ def build(self, context: BuildContext) -> FlutterWidget:
711
+ return self
712
+
713
+ def create_element(self) -> Element:
714
+ return TextFieldElement(self)
715
+
716
+
717
+ class TextFieldElement(Element[TextField, ttk.Entry]):
718
+
719
+ def __init__(self, widget: TextField) -> None:
720
+ super().__init__(widget)
721
+
722
+ def get_widget_flutter(self) -> TextField:
723
+ return self.widget_flutter
724
+
725
+ def mount(self, context: BuildContext) -> ttk.Entry:
726
+
727
+ super().mount(context)
728
+ var = tk.StringVar(value=self.get_widget_flutter().text)
729
+ entry = ttk.Entry(
730
+ context.parent_tk_widget, textvariable=var, width=self.widget_flutter.width
731
+ )
732
+
733
+ if self.get_widget_flutter().on_changed:
734
+ var.trace_add(
735
+ "write", lambda *_: self.get_widget_flutter().on_changed(var.get())
736
+ )
737
+
738
+ entry.pack(fill="x")
739
+ self.widget_tk = entry
740
+ return entry
741
+
742
+
743
+ # ============================================================
744
+ # ICON BUTTON
745
+ # ============================================================
746
+
747
+
748
+ class IconButton(StatelessWidget):
749
+
750
+ def __init__(
751
+ self, text: str, on_pressed: Callable[[], None], *, key: GlobalKey | None = None
752
+ ) -> None:
753
+ super().__init__(key)
754
+
755
+ self.text = text
756
+ self.on_pressed = on_pressed
757
+
758
+ def build(self, context: BuildContext) -> FlutterWidget:
759
+ return self
760
+
761
+ def create_element(self) -> Element:
762
+ return IconButtonElement(self)
763
+
764
+
765
+ class IconButtonElement(Element[IconButton, ttk.Button]):
766
+
767
+ def __init__(self, widget: IconButton) -> None:
768
+ super().__init__(widget)
769
+
770
+ def get_widget_flutter(self) -> IconButton:
771
+ return self.widget_flutter
772
+
773
+ def mount(self, context: BuildContext) -> ttk.Button:
774
+
775
+ super().mount(context)
776
+ button = ttk.Button(
777
+ context.parent_tk_widget,
778
+ text=self.widget_flutter.text,
779
+ command=self.widget_flutter.on_pressed,
780
+ width=3,
781
+ )
782
+
783
+ button.pack()
784
+ self.widget_tk = button
785
+ return button
786
+
787
+
788
+ # ============================================================
789
+ # CHECKBOX
790
+ # ============================================================
791
+
792
+
793
+ class Checkbox(StatelessWidget):
794
+
795
+ def __init__(
796
+ self,
797
+ value: bool = False,
798
+ text: str = "",
799
+ on_changed: Callable[[bool], None] | None = None,
800
+ *,
801
+ key: GlobalKey | None = None,
802
+ ) -> None:
803
+ super().__init__(key)
804
+
805
+ self.value = value
806
+ self.text = text
807
+ self.on_changed = on_changed
808
+
809
+ def build(self, context: BuildContext) -> FlutterWidget:
810
+ return self
811
+
812
+ def create_element(self) -> Element:
813
+ return CheckboxElement(self)
814
+
815
+
816
+ class CheckboxElement(Element[Checkbox, ttk.Checkbutton]):
817
+
818
+ def __init__(self, widget: Checkbox) -> None:
819
+ super().__init__(widget)
820
+
821
+ def get_widget_flutter(self) -> Checkbox:
822
+ return self.widget_flutter
823
+
824
+ def mount(self, context: BuildContext) -> ttk.Checkbutton:
825
+ super().mount(context)
826
+ var = tk.BooleanVar(value=self.get_widget_flutter().value)
827
+ checkbox = ttk.Checkbutton(
828
+ context.parent_tk_widget, text=self.get_widget_flutter().text, variable=var
829
+ )
830
+
831
+ if self.get_widget_flutter().on_changed:
832
+ checkbox.configure(
833
+ command=lambda: self.get_widget_flutter().on_changed(var.get())
834
+ )
835
+
836
+ checkbox.pack(anchor="w")
837
+ self.widget_tk = checkbox
838
+ return checkbox
839
+
840
+
841
+ # ============================================================
842
+ # SWITCH
843
+ # ============================================================
844
+
845
+
846
+ class Switch(Checkbox):
847
+
848
+ def __init__(
849
+ self,
850
+ value: bool = False,
851
+ text: str = "",
852
+ on_changed: Callable[[bool], None] | None = None,
853
+ *,
854
+ key: GlobalKey | None = None,
855
+ ) -> None:
856
+ super().__init__(value, text, on_changed, key=key)
857
+
858
+
859
+ # ============================================================
860
+ # IMAGE
861
+ # ============================================================
862
+
863
+
864
+ class Image(StatelessWidget):
865
+
866
+ def __init__(self, path: str, key: GlobalKey | None = None) -> None:
867
+ super().__init__(key)
868
+
869
+ self.path = path
870
+
871
+ def build(self, context: BuildContext) -> FlutterWidget:
872
+ return self
873
+
874
+ def create_element(self) -> Element:
875
+ return ImageElement(self)
876
+
877
+
878
+ class ImageElement(Element[Image, ttk.Label]):
879
+
880
+ def __init__(self, widget: Image) -> None:
881
+ super().__init__(widget)
882
+
883
+ def get_widget_flutter(self) -> Image:
884
+ return self.widget_flutter
885
+
886
+ def mount(self, context: BuildContext) -> ttk.Label:
887
+ super().mount(context)
888
+ image = tk.PhotoImage(file=self.get_widget_flutter().path)
889
+ label = ttk.Label(context.parent_tk_widget, image=image)
890
+ # label.image = image
891
+ label.pack()
892
+ self.widget_tk = label
893
+ return label
894
+
895
+
896
+ # ============================================================
897
+ # ICON
898
+ # ============================================================
899
+ class Icon(Text):
900
+
901
+ def __init__(self, text: str, key: GlobalKey | None = None) -> None:
902
+ super().__init__(text, key)
903
+
904
+
905
+ # ============================================================
906
+ # APP BAR
907
+ # ============================================================
908
+ class AppBar(StatelessWidget):
909
+
910
+ def __init__(
911
+ self,
912
+ title: str,
913
+ actions: list[FlutterWidget] | None = None,
914
+ height: int = 48,
915
+ key: GlobalKey | None = None,
916
+ ) -> None:
917
+ super().__init__(key)
918
+
919
+ self.title = title
920
+ self.actions = actions or []
921
+ self.height = height
922
+
923
+ def build(self, context: BuildContext) -> FlutterWidget:
924
+ return self
925
+
926
+ def create_element(self) -> Element:
927
+ return AppBarElement(self)
928
+
929
+
930
+ class AppBarElement(Element[AppBar, ttk.Frame]):
931
+
932
+ def __init__(self, widget: AppBar) -> None:
933
+ super().__init__(widget)
934
+ self._action_elements: list[Element] = []
935
+
936
+ def get_widget_flutter(self) -> AppBar:
937
+ return self.widget_flutter
938
+
939
+ def mount(self, context: BuildContext) -> ttk.Frame:
940
+ super().mount(context)
941
+ frame = ttk.Frame(context.parent_tk_widget)
942
+ frame.pack(fill="x")
943
+ title = ttk.Label(frame, text=self.get_widget_flutter().title)
944
+ title.pack(side="left", padx=8, pady=8)
945
+
946
+ self._action_elements = []
947
+ for action in self.get_widget_flutter().actions:
948
+ wrapper = ttk.Frame(frame)
949
+ wrapper.pack(side="right")
950
+ child = action.create_element()
951
+ child.mount(context.create_child_context(wrapper))
952
+ self._action_elements.append(child)
953
+
954
+ self.widget_tk = frame
955
+ return frame
956
+
957
+ def unmount(self) -> None:
958
+ for child in self._action_elements:
959
+ child.unmount()
960
+ self._action_elements = []
961
+ super().unmount()
962
+
963
+
964
+ # ============================================================
965
+ # SCAFFOLD
966
+ # ============================================================
967
+
968
+
969
+ class Scaffold(StatelessWidget):
970
+
971
+ def __init__(
972
+ self,
973
+ body: FlutterWidget,
974
+ *,
975
+ app_bar: AppBar | None = None,
976
+ floating_action_button: FlutterWidget | None = None,
977
+ drawer: FlutterWidget | None = None,
978
+ bottom_navigation_bar: BottomNavigationBar | None = None,
979
+ key: GlobalKey | None = None,
980
+ ) -> None:
981
+ super().__init__(key)
982
+
983
+ self.body = body
984
+ self.app_bar = app_bar
985
+ self.drawer = drawer
986
+ self.bottom_navigation_bar: BottomNavigationBar | None = bottom_navigation_bar
987
+ self.floating_action_button = floating_action_button
988
+
989
+ def build(self, context: BuildContext) -> FlutterWidget:
990
+ return self
991
+
992
+ def create_element(self) -> Element:
993
+ return ScaffoldElement(self)
994
+
995
+
996
+ class ScaffoldElement(Element[Scaffold, ttk.Frame]):
997
+
998
+ def __init__(self, widget: Scaffold) -> None:
999
+ super().__init__(widget)
1000
+ self._app_bar_element = None
1001
+ self._body_element = None
1002
+ self._bottom_nav_element = None
1003
+
1004
+ def update_widget(self, widget: FlutterWidget) -> None:
1005
+ super().update_widget(widget)
1006
+
1007
+ def update(self, new_widget: FlutterWidget) -> None:
1008
+ super().update(new_widget)
1009
+
1010
+ # old_widget = self.get_widget()
1011
+ self.widget_flutter = cast(Scaffold, new_widget)
1012
+
1013
+ # Se você quiser simplificar para testar se funciona,
1014
+ # pode desmontar e remontar tudo, ou implementar a atualização dos filhos:
1015
+ if self.widget_tk is not None:
1016
+ # Força a reconstrução do conteúdo destruindo o frame antigo e criando um novo
1017
+ context = self.get_context()
1018
+
1019
+ if context:
1020
+ self.unmount()
1021
+ self.mount(context)
1022
+
1023
+ def get_widget_flutter(self) -> Scaffold:
1024
+ return self.widget_flutter
1025
+
1026
+ def mount(self, context: BuildContext) -> ttk.Frame:
1027
+ super().mount(context)
1028
+ root_frame = ttk.Frame(context.parent_tk_widget)
1029
+ root_frame.pack(fill="both", expand=True)
1030
+
1031
+ self._app_bar_element = None
1032
+ if self.get_widget_flutter().app_bar:
1033
+ self._app_bar_element = self.get_widget_flutter().app_bar.create_element()
1034
+ self._app_bar_element.mount(context.create_child_context(root_frame))
1035
+
1036
+ # barra inferior primeiro (side="bottom"), senão o corpo (expand) a empurra para fora
1037
+ self._bottom_nav_element = None
1038
+ if self.get_widget_flutter().bottom_navigation_bar:
1039
+ self._bottom_nav_element = (
1040
+ self.get_widget_flutter().bottom_navigation_bar.create_element()
1041
+ )
1042
+ self._bottom_nav_element.mount(context.create_child_context(root_frame))
1043
+
1044
+ body_container = ttk.Frame(root_frame)
1045
+ body_container.pack(fill="both", expand=True)
1046
+
1047
+ self._body_element: Element = self.get_widget_flutter().body.create_element()
1048
+ self._body_element.mount(context.create_child_context(body_container))
1049
+
1050
+ self.widget_tk = root_frame
1051
+ return root_frame
1052
+
1053
+ def unmount(self) -> None:
1054
+ for element in (
1055
+ self._app_bar_element,
1056
+ self._body_element,
1057
+ self._bottom_nav_element,
1058
+ ):
1059
+ if element is not None:
1060
+ element.unmount()
1061
+ self._app_bar_element = self._body_element = self._bottom_nav_element = None
1062
+ super().unmount()
1063
+
1064
+
1065
+ # ============================================================
1066
+ # SAFE AREA
1067
+ # ============================================================
1068
+
1069
+
1070
+ class SafeArea(Padding):
1071
+
1072
+ def __init__(
1073
+ self, key: GlobalKey | None = None, *, padding: int, child: FlutterWidget
1074
+ ) -> None:
1075
+ super().__init__(key, padding=padding, child=child)
1076
+
1077
+
1078
+ # ============================================================
1079
+ # DRAWER
1080
+ # ============================================================
1081
+
1082
+
1083
+ class Drawer(Container):
1084
+
1085
+ def __init__(
1086
+ self,
1087
+ child: FlutterWidget | None = None,
1088
+ width: int | None = None,
1089
+ height: int | None = None,
1090
+ padding: int = 0,
1091
+ *,
1092
+ key: GlobalKey | None = None,
1093
+ ) -> None:
1094
+ super().__init__(child, width, height, padding, key=key)
1095
+
1096
+
1097
+ # ============================================================
1098
+ # BOTTOM NAVIGATION BAR
1099
+ # ============================================================
1100
+
1101
+
1102
+ class BottomNavigationBar(StatelessWidget):
1103
+
1104
+ def __init__(
1105
+ self,
1106
+ items: list[str],
1107
+ on_selected: Callable[[int], None],
1108
+ *,
1109
+ current_index: int = 0,
1110
+ key: GlobalKey | None = None,
1111
+ ) -> None:
1112
+ super().__init__(key)
1113
+ self.items = items
1114
+ self.on_selected = on_selected
1115
+ self.current_index = current_index
1116
+
1117
+ def build(self, context: BuildContext) -> FlutterWidget:
1118
+ return self
1119
+
1120
+ def create_element(self) -> Element:
1121
+ return BottomNavigationBarElement(self)
1122
+
1123
+
1124
+ class BottomNavigationBarElement(Element[BottomNavigationBar, ttk.Frame]):
1125
+
1126
+ def __init__(self, widget: BottomNavigationBar) -> None:
1127
+ super().__init__(widget)
1128
+
1129
+ def get_widget_flutter(self) -> BottomNavigationBar:
1130
+ return self.widget_flutter
1131
+
1132
+ def mount(self, context: BuildContext) -> ttk.Frame:
1133
+ super().mount(context)
1134
+ w = self.get_widget_flutter()
1135
+ frame = ttk.Frame(context.parent_tk_widget)
1136
+ frame.pack(side="bottom", fill="x") # side="bottom": nunca é cortada pelo corpo
1137
+
1138
+ for index, item in enumerate(w.items):
1139
+ style = "Elevated.TButton" if index == w.current_index else "Text.TButton"
1140
+ button = ttk.Button(
1141
+ frame,
1142
+ text=item,
1143
+ style=style,
1144
+ command=lambda i=index: w.on_selected(i),
1145
+ )
1146
+ button.pack(side="left", expand=True, fill="x")
1147
+
1148
+ self.widget_tk = frame
1149
+ return frame
1150
+
1151
+
1152
+ # ============================================================
1153
+ # WRAP
1154
+ # ============================================================
1155
+
1156
+
1157
+ class Wrap(Column):
1158
+
1159
+ def __init__(
1160
+ self,
1161
+ children: list[FlutterWidget],
1162
+ main_axis_alignment: MainAxisAlignment = MainAxisAlignment.START,
1163
+ cross_axis_alignment: CrossAxisAlignment = CrossAxisAlignment.CENTER,
1164
+ *,
1165
+ key: GlobalKey | None = None,
1166
+ ) -> None:
1167
+ super().__init__(children, main_axis_alignment, cross_axis_alignment, key=key)
1168
+
1169
+
1170
+ # ============================================================
1171
+ # STACK
1172
+ # ============================================================
1173
+
1174
+
1175
+ class Stack(StatelessWidget):
1176
+
1177
+ def __init__(
1178
+ self, children: list[FlutterWidget], *, key: GlobalKey | None = None
1179
+ ) -> None:
1180
+ super().__init__(key)
1181
+
1182
+ self.children = children
1183
+
1184
+ def build(self, context: BuildContext) -> FlutterWidget:
1185
+ return self
1186
+
1187
+ def create_element(self) -> Element:
1188
+ return StackElement(self)
1189
+
1190
+
1191
+ class StackElement(Element[Stack, ttk.Frame]):
1192
+
1193
+ def __init__(self, widget: Stack) -> None:
1194
+ super().__init__(widget)
1195
+
1196
+ def get_widget_flutter(self) -> Stack:
1197
+ return self.widget_flutter
1198
+
1199
+ def mount(self, context: BuildContext) -> ttk.Frame:
1200
+ super().mount(context)
1201
+ frame = ttk.Frame(context.parent_tk_widget)
1202
+ frame.pack(fill="both", expand=True)
1203
+
1204
+ for child in self.get_widget_flutter().children:
1205
+ wrapper = ttk.Frame(frame)
1206
+ wrapper.place(relx=0, rely=0, relwidth=1, relheight=1)
1207
+
1208
+ inflate_widget(child, context).mount(context.create_child_context(wrapper))
1209
+
1210
+ self.widget_tk = frame
1211
+ return frame
1212
+
1213
+
1214
+ # ============================================================
1215
+ # POSITIONED
1216
+ # ============================================================
1217
+ class Positioned(StatelessWidget):
1218
+
1219
+ def __init__(
1220
+ self,
1221
+ child: FlutterWidget,
1222
+ x: int = 0,
1223
+ y: int = 0,
1224
+ *,
1225
+ key: GlobalKey | None = None,
1226
+ ) -> None:
1227
+ super().__init__(key)
1228
+
1229
+ self.child = child
1230
+ self.x = x
1231
+ self.y = y
1232
+
1233
+ def build(self, context: BuildContext) -> FlutterWidget:
1234
+ return self.child
1235
+
1236
+ def create_element(self) -> Element:
1237
+ return inflate_widget(self.child, self.context)
1238
+
1239
+
1240
+ # ============================================================
1241
+ # VISIBILITY
1242
+ # ============================================================
1243
+ class Visibility(StatelessWidget):
1244
+
1245
+ def __init__(self, visible: bool, child: FlutterWidget) -> None:
1246
+ super().__init__()
1247
+ self.visible = visible
1248
+ self.child = child
1249
+
1250
+ def build(self, context: BuildContext) -> FlutterWidget:
1251
+ if self.visible:
1252
+ return self.child
1253
+ return SizedBox()
1254
+
1255
+ def create_element(self) -> Element:
1256
+ return self.build(None).create_element()
1257
+
1258
+
1259
+ # ============================================================
1260
+ # FUTURE BUILDER
1261
+ # ============================================================
1262
+
1263
+
1264
+ class FutureBuilder(StatelessWidget):
1265
+
1266
+ def __init__(
1267
+ self,
1268
+ future: Callable[[], object],
1269
+ builder: Callable[[BuildContext, object], FlutterWidget],
1270
+ *,
1271
+ key: GlobalKey | None = None,
1272
+ ) -> None:
1273
+ super().__init__(key)
1274
+
1275
+ self.future = future
1276
+ self.builder = builder
1277
+
1278
+ def build(self, context: BuildContext) -> FlutterWidget:
1279
+ result = self.future()
1280
+ return self.builder(context, result)
1281
+
1282
+ def create_element(self) -> Element:
1283
+ return self.build(None).create_element()