在线代码实验室
运行三棵树/InheritedWidget、RepaintBoundary/Keys、CustomPainter 画布与 Stream/Isolate 消息通道离线核验
"""Offline Flutter Advanced Architecture (3-Tree Rendering, InheritedWidget, RepaintBoundary, Keys, CustomPainter, Stream/Future & Isolate message passing) verifier for Ch25 (advanced)."""
import json
import queue
import threading
VERSION = "CPython 3.12.14 offline Flutter/Dart architecture & runtime verifier (Flutter SDK absent)"
def check(name, summary, expected, actual):
return {
"name": name,
"summary": summary,
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = []
# Case 1: Three-tree architecture (Widget -> Element -> RenderObject) & InheritedWidget updateShouldNotify
trees = [
{"name": "Widget", "mutable": False, "role": "configuration"},
{"name": "Element", "mutable": True, "role": "lifecycle_and_context"},
{"name": "RenderObject", "mutable": True, "role": "layout_and_paint"},
]
class MyDataInherited:
def __init__(self, value):
self.value = value
self.dependents = []
def depend(self, child_cb):
self.dependents.append(child_cb)
return self.value
def update(self, new_value):
should_notify = new_value != self.value
self.value = new_value
if should_notify:
for cb in self.dependents:
cb(new_value)
return should_notify
notified_values = []
inherited = MyDataInherited(42)
initial_read = inherited.depend(lambda v: notified_values.append(v))
same_notify = inherited.update(42)
diff_notify = inherited.update(99)
cases.append(
check(
"three_trees_and_inherited_widget",
"Verify Widget/Element/RenderObject mutability roles and InheritedWidget.updateShouldNotify(42->42 False, 42->99 True)",
{
"tree_mutability": {"Widget": False, "Element": True, "RenderObject": True},
"initial_read": 42,
"same_value_notifies": False,
"new_value_notifies": True,
"notified_values": [99],
},
{
"tree_mutability": {t["name"]: t["mutable"] for t in trees},
"initial_read": initial_read,
"same_value_notifies": same_notify,
"new_value_notifies": diff_notify,
"notified_values": notified_values,
},
)
)
# Case 2: RepaintBoundary dirty-layer isolation & ValueKey vs ObjectKey vs UniqueKey equality
# Parent layer (outer) vs isolated RepaintBoundary child layer (inner)
repaints = {"outer_layer": 0, "inner_boundary_layer": 0}
def mark_inner_dirty(has_repaint_boundary):
repaints["inner_boundary_layer"] += 1
if not has_repaint_boundary:
repaints["outer_layer"] += 1
for _ in range(3):
mark_inner_dirty(has_repaint_boundary=True)
obj_a = {"id": 1}
obj_b = {"id": 1}
key_matches = {
"ValueKey_equal_value": ("v", 1) == ("v", 1),
"ObjectKey_same_ref": id(obj_a) == id(obj_a),
"ObjectKey_diff_ref": id(obj_a) == id(obj_b),
"UniqueKey_always_distinct": object() == object(),
}
cases.append(
check(
"repaint_boundary_and_keys_semantics",
"Verify RepaintBoundary keeps outer_layer repaints at 0 across 3 inner ticks, plus ValueKey/ObjectKey/UniqueKey identity",
{
"repaints": {"outer_layer": 0, "inner_boundary_layer": 3},
"key_matches": {
"ValueKey_equal_value": True,
"ObjectKey_same_ref": True,
"ObjectKey_diff_ref": False,
"UniqueKey_always_distinct": False,
},
},
{"repaints": repaints, "key_matches": key_matches},
)
)
# Case 3: CustomPainter drawCircle geometry (size 200x200 -> center (100,100), radius 90, fill + stroke)
size_w, size_h = 200.0, 200.0
canvas_cmds = []
center = [size_w / 2.0, size_h / 2.0]
radius = size_w / 2.0 - 10.0
canvas_cmds.append({"op": "drawCircle", "center": center, "radius": radius, "style": "fill", "color": "blue"})
canvas_cmds.append({"op": "drawCircle", "center": center, "radius": radius, "style": "stroke", "strokeWidth": 2})
should_repaint = False
cases.append(
check(
"custom_painter_canvas_commands",
"Verify MyCirclePainter records 2 drawCircle ops (fill + 2px stroke) at center (100,100), radius 90, shouldRepaint=false",
{"cmd_count": 2, "center": [100.0, 100.0], "radius": 90.0, "should_repaint": False},
{"cmd_count": len(canvas_cmds), "center": center, "radius": radius, "should_repaint": should_repaint},
)
)
# Case 4: Stream async* generator & Dart Isolate message-passing concurrency (no shared mutable memory)
def count_stream(max_val):
for i in range(1, max_val + 1):
yield i
stream_events = list(count_stream(5))
# Isolated worker communicating strictly via serialized JSON message queues (SendPort / ReceivePort model)
send_port = queue.Queue()
receive_port = queue.Queue()
def isolate_worker():
raw_msg = send_port.get()
payload = json.loads(raw_msg) # isolated memory copy
total = sum(x * x for x in payload["numbers"])
receive_port.put(json.dumps({"sum_of_squares": total}))
t = threading.Thread(target=isolate_worker)
t.start()
send_port.put(json.dumps({"numbers": [1, 2, 3, 4, 5]}))
result_msg = json.loads(receive_port.get(timeout=5))
t.join(timeout=5)
cases.append(
check(
"stream_async_star_and_isolate_messaging",
"Verify async* Stream yielding [1..5] and Isolate JSON SendPort/ReceivePort message-passing sum_of_squares=55",
{"stream_events": [1, 2, 3, 4, 5], "isolate_sum_of_squares": 55},
{"stream_events": stream_events, "isolate_sum_of_squares": result_msg["sum_of_squares"]},
)
)
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/flutter-advanced-lab/explore-advanced.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-advanced.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1986.zip
课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a1988.zip