蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 setState、Provider watch/read 重建隔离、MultiProvider 与状态提升单向数据流离线核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-state-management.py
explore-state-management.py160 行
"""Offline Flutter State Management (setState, Provider/ChangeNotifier, MultiProvider, Lifting State Up) verifier for Ch11 (state-management)."""
import json

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,
    }


class ChangeNotifier:
    def __init__(self):
        self._listeners = []

    def add_listener(self, cb):
        self._listeners.append(cb)

    def notify_listeners(self):
        for cb in list(self._listeners):
            cb()


class CounterModel(ChangeNotifier):
    def __init__(self):
        super().__init__()
        self._count = 0

    @property
    def count(self):
        return self._count

    def increment(self):
        self._count += 1
        self.notify_listeners()

    def decrement(self):
        self._count -= 1
        self.notify_listeners()


class UserModel(ChangeNotifier):
    def __init__(self, username="alice"):
        super().__init__()
        self.username = username

    def logout(self):
        self.username = None
        self.notify_listeners()


class CartModel(ChangeNotifier):
    def __init__(self):
        super().__init__()
        self.items = []

    def add(self, item):
        self.items.append(item)
        self.notify_listeners()


def main():
    cases = []

    # Case 1: Ephemeral/local state with setState (+/- counter)
    local_count = 0
    local_builds = 1
    for delta in (1, 1, 1, -1):
        local_count += delta
        local_builds += 1
    cases.append(
        check(
            "local_setstate_counter",
            "Verify ephemeral local state increment/decrement and rebuild count",
            {"count": 2, "builds": 5},
            {"count": local_count, "builds": local_builds},
        )
    )

    # Case 2: Provider + ChangeNotifier watch vs read rebuild discipline
    counter = CounterModel()
    watch_rebuilds = 0
    read_rebuilds = 0

    def on_watch():
        nonlocal watch_rebuilds
        watch_rebuilds += 1

    # context.watch subscribes; context.read does NOT subscribe
    counter.add_listener(on_watch)
    counter.increment()
    counter.increment()
    counter.decrement()
    cases.append(
        check(
            "provider_change_notifier_watch_vs_read",
            "Verify ChangeNotifier.notifyListeners() rebuilds watching widgets (3x) while context.read listeners stay at 0",
            {"final_count": 1, "watch_rebuilds": 3, "read_rebuilds": 0},
            {"final_count": counter.count, "watch_rebuilds": watch_rebuilds, "read_rebuilds": read_rebuilds},
        )
    )

    # Case 3: MultiProvider registry isolating UserModel, ThemeModel, CartModel
    providers = {"UserModel": UserModel("zhangsan"), "ThemeModel": {"mode": "light"}, "CartModel": CartModel()}
    user_notifies = []
    cart_notifies = []
    providers["UserModel"].add_listener(lambda: user_notifies.append(providers["UserModel"].username))
    providers["CartModel"].add_listener(lambda: cart_notifies.append(len(providers["CartModel"].items)))

    providers["CartModel"].add("Flutter Book")
    providers["UserModel"].logout()
    cases.append(
        check(
            "multi_provider_isolation",
            "Verify MultiProvider scopes notifications independently per model (CartModel vs UserModel)",
            {"cart_notifies": [1], "user_notifies": [None], "provider_count": 3},
            {"cart_notifies": cart_notifies, "user_notifies": user_notifies, "provider_count": len(providers)},
        )
    )

    # Case 4: Lifting State Up (Parent owns _isEnabled; ChildA reads; ChildB invokes callback)
    parent_state = {"isEnabled": False}
    child_a_renders = []

    def render_parent():
        enabled = parent_state["isEnabled"]
        child_a_renders.append("开启" if enabled else "关闭")
        return {"child_a": child_a_renders[-1], "child_b_button": "关闭" if enabled else "开启"}

    def child_b_tap():
        parent_state["isEnabled"] = not parent_state["isEnabled"]
        return render_parent()

    s0 = render_parent()
    s1 = child_b_tap()
    s2 = child_b_tap()
    cases.append(
        check(
            "lifting_state_up_unidirectional_flow",
            "Verify unidirectional data flow: Parent holds isEnabled, ChildB triggers onToggle, ChildA reflects updates",
            {
                "initial": {"child_a": "关闭", "child_b_button": "开启"},
                "after_first_toggle": {"child_a": "开启", "child_b_button": "关闭"},
                "after_second_toggle": {"child_a": "关闭", "child_b_button": "开启"},
            },
            {"initial": s0, "after_first_toggle": s1, "after_second_toggle": s2},
        )
    )

    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-state-management-lab/explore-state-management.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-state-management.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Flutter

课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a1988.zip

下载课程关联工程包:Flutter

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2004.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习