"""Offline Flutter Best Practices (naming lints, const canonicalization, ValueKey diffing, lazy ListView & global error handling) verifier for Ch23 (best-practices)."""
import json
import re
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 check_naming_rules(class_name, fn_name, const_name, file_name):
return {
"class_pascal": bool(re.match(r"^[A-Z][a-zA-Z0-9]*$", class_name)),
"fn_camel": bool(re.match(r"^[a-z][a-zA-Z0-9]*$", fn_name)),
"const_k_prefix": bool(re.match(r"^k[A-Z][a-zA-Z0-9]*$", const_name)),
"file_snake": bool(re.match(r"^[a-z][a-z0-9_]*\.dart$", file_name)),
}
def main():
cases = []
# Case 1: Dart/Flutter naming conventions validator
res = check_naming_rules("UserProfilePage", "fetchUserData", "kMaxRetryCount", "user_profile_page.dart")
bad = check_naming_rules("user_page", "FetchData", "MAX_COUNT", "UserPage.dart")
cases.append(
check(
"dart_naming_convention_linter",
"Verify UpperCamelCase classes, lowerCamelCase functions/vars, k-prefixed constants, and snake_case .dart filenames",
{
"valid_all": True,
"invalid_all_rejected": True,
},
{
"valid_all": all(res.values()),
"invalid_all_rejected": not any(bad.values()),
},
)
)
# Case 2: const widget canonicalization reducing rebuild allocations
const_pool = {}
def create_widget(label, is_const):
if is_const:
key = ("Text", label)
if key not in const_pool:
const_pool[key] = {"type": "Text", "label": label, "id": len(const_pool) + 1}
return const_pool[key]
return {"type": "Text", "label": label, "id": object()}
c_objs = [create_widget("Hello", True) for _ in range(5)]
nc_objs = [create_widget("Hello", False) for _ in range(5)]
cases.append(
check(
"const_widget_canonicalization",
"Verify const Text('Hello') reuses 1 canonical instance across 5 builds while non-const allocates 5 distinct instances",
{"const_unique_instances": 1, "non_const_unique_instances": 5},
{
"const_unique_instances": len({id(o) for o in c_objs}),
"non_const_unique_instances": len({id(o) for o in nc_objs}),
},
)
)
# Case 3: ValueKey reconciliation preserving element state when deleting head item + lazy ListView.builder savings
# Before delete: [item(id=1, state='A'), item(id=2, state='B'), item(id=3, state='C')]
old_elements = {"1": "state_A", "2": "state_B", "3": "state_C"}
new_ids = ["2", "3"]
matched_by_key = [old_elements[k] for k in new_ids]
# Lazy builder vs eager List.generate(1000)
eager_built = 1000
lazy_built = 12 # visible viewport items
cases.append(
check(
"value_key_diff_and_lazy_builder",
"Verify ValueKey preserves state_B/state_C after removing id=1 and ListView.builder cuts initial builds from 1000 to 12",
{"preserved_states": ["state_B", "state_C"], "memory_reduction_pct": 98.8},
{"preserved_states": matched_by_key, "memory_reduction_pct": round((1 - lazy_built / eager_built) * 100, 1)},
)
)
# Case 4: Layered project structure & global error routing (FlutterError.onError + runZonedGuarded)
reported = []
def report_error(source, exc):
reported.append(f"{source}:{exc}")
# Simulate framework build error & uncaught async zone error
report_error("FlutterError", "RenderFlex overflowed by 24 pixels")
report_error("ZoneError", "SocketException: Connection refused")
lib_layers = ["core", "data", "domain", "presentation", "routes"]
cases.append(
check(
"project_layers_and_global_error_trap",
"Verify Clean Architecture 5 lib/ layers and dual error capture (FlutterError.onError + runZonedGuarded)",
{
"layer_count": 5,
"captured_sources": ["FlutterError", "ZoneError"],
"reported_count": 2,
},
{
"layer_count": len(lib_layers),
"captured_sources": [r.split(":")[0] for r in reported],
"reported_count": len(reported),
},
)
)
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-best-practices-lab/explore-best-practices.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-best-practices.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1989.zip
课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a1988.zip