"""Offline Flutter project structure & pubspec.yaml dependency/asset verifier for Ch04 (project-structure)."""
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,
}
SAMPLE_PUBSPEC = """
name: my_app
version: 1.0.0+1
description: "我的第一个 Flutter 应用"
environment:
sdk: ^3.0.0
dependencies:
flutter:
sdk: flutter
http: ^1.0.0
provider: ^6.0.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^3.0.0
flutter:
uses-material-design: true
assets:
- images/
- assets/data.json
"""
def parse_pubspec(text):
data = {"dependencies": {}, "dev_dependencies": {}, "flutter_assets": [], "uses_material_design": False}
section = None
in_assets = False
for raw in text.splitlines():
if not raw.strip() or raw.strip().startswith("#"):
continue
indent = len(raw) - len(raw.lstrip(" "))
line = raw.strip()
if indent == 0:
in_assets = False
k, _, v = line.partition(":")
v = v.strip().strip('"')
if v:
data[k] = v
section = None
else:
section = k
elif indent == 2:
if section in ("dependencies", "dev_dependencies"):
k, _, v = line.partition(":")
data[section][k.strip()] = v.strip() or "sdk"
elif section == "environment":
k, _, v = line.partition(":")
data["sdk"] = v.strip()
elif section == "flutter":
k, _, v = line.partition(":")
if k.strip() == "uses-material-design":
data["uses_material_design"] = v.strip().lower() == "true"
elif k.strip() == "assets":
in_assets = True
elif indent >= 4 and in_assets and line.startswith("- "):
data["flutter_assets"].append(line[2:].strip())
return data
def satisfies_caret(constraint, version):
# Semver caret ^X.Y.Z: >= X.Y.Z and < (X+1).0.0 (for X >= 1)
base = tuple(int(p) for p in constraint.lstrip("^").split("."))
ver = tuple(int(p) for p in version.split("."))
upper = (base[0] + 1, 0, 0) if base[0] > 0 else (0, base[1] + 1, 0)
return base <= ver < upper
def main():
cases = []
# Case 1: Standard top-level directory layout verification
top_level = {
"lib": "dart_core",
"android": "android_native",
"ios": "ios_xcode",
"web": "web_target",
"windows": "windows_desktop",
"macos": "macos_desktop",
"linux": "linux_desktop",
"test": "automated_tests",
}
cases.append(
check(
"project_top_level_directories",
"Verify standard flutter create top-level directories covering lib, test, and 6 platform folders",
{"total_dirs": 8, "platform_dirs": 6, "has_lib_and_test": True},
{
"total_dirs": len(top_level),
"platform_dirs": sum(1 for k in top_level if k not in ("lib", "test")),
"has_lib_and_test": "lib" in top_level and "test" in top_level,
},
)
)
# Case 2: pubspec.yaml parsing (name, version+build, dependencies, dev_dependencies, assets)
parsed = parse_pubspec(SAMPLE_PUBSPEC)
ver_match = re.match(r"^(\d+\.\d+\.\d+)\+(\d+)$", parsed["version"])
cases.append(
check(
"pubspec_yaml_parser",
"Parse pubspec.yaml fields: snake_case name, semver+build version, runtime/dev dependencies, and flutter.assets",
{
"name": "my_app",
"semver": "1.0.0",
"build_number": 1,
"runtime_pkgs": ["flutter", "http", "provider"],
"dev_pkgs": ["flutter_test", "flutter_lints"],
"assets": ["images/", "assets/data.json"],
"uses_material_design": True,
},
{
"name": parsed["name"],
"semver": ver_match.group(1),
"build_number": int(ver_match.group(2)),
"runtime_pkgs": list(parsed["dependencies"].keys()),
"dev_pkgs": list(parsed["dev_dependencies"].keys()),
"assets": parsed["flutter_assets"],
"uses_material_design": parsed["uses_material_design"],
},
)
)
# Case 3: Dependency lifecycle commands & caret semver solver
deps = dict(parsed["dependencies"])
# Simulate flutter pub add dio & flutter pub remove provider
deps["dio"] = "^5.4.0"
deps.pop("provider")
caret_checks = {
"http_1_2_1_ok": satisfies_caret("^1.0.0", "1.2.1"),
"http_2_0_0_ok": satisfies_caret("^1.0.0", "2.0.0"),
"sdk_3_24_0_ok": satisfies_caret("^3.0.0", "3.24.0"),
}
cases.append(
check(
"pub_dependency_solver",
"Verify flutter pub add/remove mutation and Dart caret (^x.y.z) version range semantics",
{
"after_add_remove": ["flutter", "http", "dio"],
"caret_checks": {"http_1_2_1_ok": True, "http_2_0_0_ok": False, "sdk_3_24_0_ok": True},
},
{"after_add_remove": list(deps.keys()), "caret_checks": caret_checks},
)
)
# Case 4: Layered Clean Architecture directory verification
layered_lib = {
"core": ["constants", "theme", "utils"],
"data": ["models", "repositories", "services"],
"domain": ["entities"],
"presentation": ["pages", "widgets", "providers"],
"routes": [],
}
cases.append(
check(
"layered_lib_architecture",
"Verify recommended scalable lib/ directory partitioning across core, data, domain, presentation, and routes",
{"top_layers": 5, "total_submodules": 10},
{"top_layers": len(layered_lib), "total_submodules": sum(len(v) for v in layered_lib.values())},
)
)
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-project-structure-lab/explore-project-structure.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-project-structure.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2003.zip
课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a1988.zip