[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AKYV8RHJ0NH416D7ZTN5B6":3,"skill-same:01M7AKYV8RHJ0NH416D7ZTN5B6":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M7AKYV8RHJ0NH416D7ZTN5B6","dart-flutter-patterns",null,"生产就绪的 Dart 和 Flutter 模式，涵盖空安全、不可变状态、异步组合、Widget 架构、流行的状态管理框架（BLoC、Riverpod、Provider）、GoRouter 导航、Dio 网络请求、Freezed 代码生成和整洁架构。","Cyrilthetecchieee\u002Fcyril-code-","Cyrilthetecchieee","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F219787998?v=4","01M7AF0MMMKRAA0H61XMJPV92H","Julian Cyril D ","01M7AF0MQ10AVG6QJQ1C2BC0F5",2,"MIT","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fdocs\u002Fzh-CN\u002Fskills\u002Fdart-flutter-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: dart-flutter-patterns\ndescription: 生产就绪的 Dart 和 Flutter 模式，涵盖空安全、不可变状态、异步组合、Widget 架构、流行的状态管理框架（BLoC、Riverpod、Provider）、GoRouter 导航、Dio 网络请求、Freezed 代码生成和整洁架构。\norigin: ECC\n---\n\n# Dart\u002FFlutter 模式\n\n## 使用场景\n\n在以下情况使用此技能：\n\n* 开始新的 Flutter 功能，需要状态管理、导航或数据访问的惯用模式\n* 审查或编写 Dart 代码，需要空安全、密封类型或异步组合的指导\n* 搭建新的 Flutter 项目，在 BLoC、Riverpod 或 Provider 之间做选择\n* 实现安全的 HTTP 客户端、WebView 集成或本地存储\n* 为 Flutter 组件、Cubit 或 Riverpod 提供者编写测试\n* 使用认证守卫配置 GoRouter\n\n## 工作原理\n\n此技能提供按关注点组织的、可直接复制粘贴的 Dart\u002FFlutter 代码模式：\n\n1. **空安全** — 避免 `!`，优先使用 `?.`\u002F`??`\u002F模式匹配\n2. **不可变状态** — 密封类、`freezed`、`copyWith`\n3. **异步组合** — 并发 `Future.wait`、`BuildContext` 后安全使用 `await`\n4. **组件架构** — 提取为类（而非方法）、`const` 传播、作用域重建\n5. **状态管理** — BLoC\u002FCubit 事件、Riverpod 通知器和派生提供者\n6. **导航** — 通过 `refreshListenable` 实现带响应式认证守卫的 GoRouter\n7. **网络请求** — 带拦截器的 Dio、带一次性重试守卫的令牌刷新\n8. **错误处理** — 全局捕获、`ErrorWidget.builder`、Crashlytics 集成\n9. **测试** — 单元测试（BLoC 测试）、组件测试（ProviderScope 覆盖）、使用假对象而非模拟对象\n\n## 示例\n\n```dart\n\u002F\u002F Sealed state — prevents impossible states\nsealed class AsyncState\u003CT> {}\nfinal class Loading\u003CT> extends AsyncState\u003CT> {}\nfinal class Success\u003CT> extends AsyncState\u003CT> { final T data; const Success(this.data); }\nfinal class Failure\u003CT> extends AsyncState\u003CT> { final Object error; const Failure(this.error); }\n\n\u002F\u002F GoRouter with reactive auth redirect\nfinal router = GoRouter(\n  refreshListenable: GoRouterRefreshStream(authCubit.stream),\n  redirect: (context, state) {\n    final authed = context.read\u003CAuthCubit>().state is AuthAuthenticated;\n    if (!authed && !state.matchedLocation.startsWith('\u002Flogin')) return '\u002Flogin';\n    return null;\n  },\n  routes: [...],\n);\n\n\u002F\u002F Riverpod derived provider with safe firstWhereOrNull\n@riverpod\ndouble cartTotal(Ref ref) {\n  final cart = ref.watch(cartNotifierProvider);\n  final products = ref.watch(productsProvider).valueOrNull ?? [];\n  return cart.fold(0.0, (total, item) {\n    final product = products.firstWhereOrNull((p) => p.id == item.productId);\n    return total + (product?.price ?? 0) * item.quantity;\n  });\n}\n```\n\n***\n\n适用于 Dart 和 Flutter 应用程序的实用、生产就绪模式。尽可能保持库无关性，并明确覆盖最常见的生态系统包。\n\n***\n\n## 1. 空安全基础\n\n### 优先使用模式而非感叹号操作符\n\n```dart\n\u002F\u002F BAD — crashes at runtime if null\nfinal name = user!.name;\n\n\u002F\u002F GOOD — provide fallback\nfinal name = user?.name ?? 'Unknown';\n\n\u002F\u002F GOOD — Dart 3 pattern matching (preferred for complex cases)\nfinal display = switch (user) {\n  User(:final name, :final email) => '$name \u003C$email>',\n  null => 'Guest',\n};\n\n\u002F\u002F GOOD — guard early return\nString getUserName(User? user) {\n  if (user == null) return 'Unknown';\n  return user.name; \u002F\u002F promoted to non-null after check\n}\n```\n\n### 避免过度使用 `late`\n\n```dart\n\u002F\u002F BAD — defers null error to runtime\nlate String userId;\n\n\u002F\u002F GOOD — nullable with explicit initialization\nString? userId;\n\n\u002F\u002F OK — use late only when initialization is guaranteed before first access\n\u002F\u002F (e.g., in initState() before any widget interaction)\nlate final AnimationController _controller;\n\n@override\nvoid initState() {\n  super.initState();\n  _controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 300));\n}\n```\n\n***\n\n## 2. 不可变状态\n\n### 状态层次结构的密封类\n\n```dart\nsealed class UserState {}\n\nfinal class UserInitial extends UserState {}\n\nfinal class UserLoading extends UserState {}\n\nfinal class UserLoaded extends UserState {\n  const UserLoaded(this.user);\n  final User user;\n}\n\nfinal class UserError extends UserState {\n  const UserError(this.message);\n  final String message;\n}\n\n\u002F\u002F Exhaustive switch — compiler enforces all branches\nWidget buildFrom(UserState state) => switch (state) {\n  UserInitial() => const SizedBox.shrink(),\n  UserLoading() => const CircularProgressIndicator(),\n  UserLoaded(:final user) => UserCard(user: user),\n  UserError(:final message) => ErrorText(message),\n};\n```\n\n### 使用 Freezed 实现无模板代码的不可变性\n\n```dart\nimport 'package:freezed_annotation\u002Ffreezed_annotation.dart';\n\npart 'user.freezed.dart';\npart 'user.g.dart';\n\n@freezed\nclass User with _$User {\n  const factory User({\n    required String id,\n    required String name,\n    required String email,\n    @Default(false) bool isAdmin,\n  }) = _User;\n\n  factory User.fromJson(Map\u003CString, dynamic> json) => _$UserFromJson(json);\n}\n\n\u002F\u002F Usage\nfinal user = User(id: '1', name: 'Alice', email: 'alice@example.com');\nfinal updated = user.copyWith(name: 'Alice Smith'); \u002F\u002F immutable update\nfinal json = user.toJson();\nfinal fromJson = User.fromJson(json);\n```\n\n***\n\n## 3. 异步组合\n\n### 使用 Future.wait 的结构化并发\n\n```dart\nFuture\u003CDashboardData> loadDashboard(UserRepository users, OrderRepository orders) async {\n  \u002F\u002F Run concurrently — don't await sequentially\n  final (userList, orderList) = await (\n    users.getAll(),\n    orders.getRecent(),\n  ).wait; \u002F\u002F Dart 3 record destructuring + Future.wait extension\n\n  return DashboardData(users: userList, orders: orderList);\n}\n```\n\n### 流模式\n\n```dart\n\u002F\u002F Repository exposes reactive streams for live data\nStream\u003CList\u003CItem>> watchCartItems() => _db\n    .watchTable('cart_items')\n    .map((rows) => rows.map(Item.fromRow).toList());\n\n\u002F\u002F In widget layer — declarative, no manual subscription\nStreamBuilder\u003CList\u003CItem>>(\n  stream: cartRepository.watchCartItems(),\n  builder: (context, snapshot) => switch (snapshot) {\n    AsyncSnapshot(connectionState: ConnectionState.waiting) =>\n        const CircularProgressIndicator(),\n    AsyncSnapshot(:final error?) => ErrorWidget(error.toString()),\n    AsyncSnapshot(:final data?) => CartList(items: data),\n    _ => const SizedBox.shrink(),\n  },\n)\n```\n\n### Await 后的 BuildContext\n\n```dart\n\u002F\u002F CRITICAL — always check mounted after any await in StatefulWidget\nFuture\u003Cvoid> _handleSubmit() async {\n  setState(() => _isLoading = true);\n  try {\n    await authService.login(_email, _password);\n    if (!mounted) return; \u002F\u002F ← guard before using context\n    context.go('\u002Fhome');\n  } on AuthException catch (e) {\n    if (!mounted) return;\n    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(e.message)));\n  } finally {\n    if (mounted) setState(() => _isLoading = false);\n  }\n}\n```\n\n***\n\n## 4. 组件架构\n\n### 提取为类，而非方法\n\n```dart\n\u002F\u002F BAD — private method returning widget, prevents optimization\nWidget _buildHeader() {\n  return Container(\n    padding: const EdgeInsets.all(16),\n    child: Text(title, style: Theme.of(context).textTheme.headlineMedium),\n  );\n}\n\n\u002F\u002F GOOD — separate widget class, enables const, element reuse\nclass _PageHeader extends StatelessWidget {\n  const _PageHeader(this.title);\n  final String title;\n\n  @override\n  Widget build(BuildContext context) {\n    return Container(\n      padding: const EdgeInsets.all(16),\n      child: Text(title, style: Theme.of(context).textTheme.headlineMedium),\n    );\n  }\n}\n```\n\n### const 传播\n\n```dart\n\u002F\u002F BAD — new instances every rebuild\nchild: Padding(\n  padding: EdgeInsets.all(16.0),       \u002F\u002F not const\n  child: Icon(Icons.home, size: 24.0), \u002F\u002F not const\n)\n\n\u002F\u002F GOOD — const stops rebuild propagation\nchild: const Padding(\n  padding: EdgeInsets.all(16.0),\n  child: Icon(Icons.home, size: 24.0),\n)\n```\n\n### 作用域重建\n\n```dart\n\u002F\u002F BAD — entire page rebuilds on every counter change\nclass CounterPage extends ConsumerWidget {\n  @override\n  Widget build(BuildContext context, WidgetRef ref) {\n    final count = ref.watch(counterProvider); \u002F\u002F rebuilds everything\n    return Scaffold(\n      body: Column(children: [\n        const ExpensiveHeader(), \u002F\u002F unnecessarily rebuilt\n        Text('$count'),\n        const ExpensiveFooter(), \u002F\u002F unnecessarily rebuilt\n      ]),\n    );\n  }\n}\n\n\u002F\u002F GOOD — isolate the rebuilding part\nclass CounterPage extends StatelessWidget {\n  const CounterPage({super.key});\n\n  @override\n  Widget build(BuildContext context) {\n    return const Scaffold(\n      body: Column(children: [\n        ExpensiveHeader(),        \u002F\u002F never rebuilt (const)\n        _CounterDisplay(),        \u002F\u002F only this rebuilds\n        ExpensiveFooter(),        \u002F\u002F never rebuilt (const)\n      ]),\n    );\n  }\n}\n\nclass _CounterDisplay extends ConsumerWidget {\n  const _CounterDisplay();\n\n  @override\n  Widget build(BuildContext context, WidgetRef ref) {\n    final count = ref.watch(counterProvider);\n    return Text('$count');\n  }\n}\n```\n\n***\n\n## 5. 状态管理：BLoC\u002FCubit\n\n```dart\n\u002F\u002F Cubit — synchronous or simple async state\nclass AuthCubit extends Cubit\u003CAuthState> {\n  AuthCubit(this._authService) : super(const AuthState.initial());\n  final AuthService _authService;\n\n  Future\u003Cvoid> login(String email, String password) async {\n    emit(const AuthState.loading());\n    try {\n      final user = await _authService.login(email, password);\n      emit(AuthState.authenticated(user));\n    } on AuthException catch (e) {\n      emit(AuthState.error(e.message));\n    }\n  }\n\n  void logout() {\n    _authService.logout();\n    emit(const AuthState.initial());\n  }\n}\n\n\u002F\u002F In widget\nBlocBuilder\u003CAuthCubit, AuthState>(\n  builder: (context, state) => switch (state) {\n    AuthInitial() => const LoginForm(),\n    AuthLoading() => const CircularProgressIndicator(),\n    AuthAuthenticated(:final user) => HomePage(user: user),\n    AuthError(:final message) => ErrorView(message: message),\n  },\n)\n```\n\n***\n\n## 6. 状态管理：Riverpod\n\n```dart\n\u002F\u002F Auto-dispose async provider\n@riverpod\nFuture\u003CList\u003CProduct>> products(Ref ref) async {\n  final repo = ref.watch(productRepositoryProvider);\n  return repo.getAll();\n}\n\n\u002F\u002F Notifier with complex mutations\n@riverpod\nclass CartNotifier extends _$CartNotifier {\n  @override\n  List\u003CCartItem> build() => [];\n\n  void add(Product product) {\n    final existing = state.where((i) => i.productId == product.id).firstOrNull;\n    if (existing != null) {\n      state = [\n        for (final item in state)\n          if (item.productId == product.id) item.copyWith(quantity: item.quantity + 1)\n          else item,\n      ];\n    } else {\n      state = [...state, CartItem(productId: product.id, quantity: 1)];\n    }\n  }\n\n  void remove(String productId) =>\n      state = state.where((i) => i.productId != productId).toList();\n\n  void clear() => state = [];\n}\n\n\u002F\u002F Derived provider (selector pattern)\n@riverpod\nint cartCount(Ref ref) => ref.watch(cartNotifierProvider).length;\n\n@riverpod\ndouble cartTotal(Ref ref) {\n  final cart = ref.watch(cartNotifierProvider);\n  final products = ref.watch(productsProvider).valueOrNull ?? [];\n  return cart.fold(0.0, (total, item) {\n    \u002F\u002F firstWhereOrNull (from collection package) avoids StateError when product is missing\n    final product = products.firstWhereOrNull((p) => p.id == item.productId);\n    return total + (product?.price ?? 0) * item.quantity;\n  });\n}\n```\n\n***\n\n## 7. 使用 GoRouter 的导航\n\n```dart\nfinal router = GoRouter(\n  initialLocation: '\u002F',\n  \u002F\u002F refreshListenable re-evaluates redirect whenever auth state changes\n  refreshListenable: GoRouterRefreshStream(authCubit.stream),\n  redirect: (context, state) {\n    final isLoggedIn = context.read\u003CAuthCubit>().state is AuthAuthenticated;\n    final isGoingToLogin = state.matchedLocation == '\u002Flogin';\n    if (!isLoggedIn && !isGoingToLogin) return '\u002Flogin';\n    if (isLoggedIn && isGoingToLogin) return '\u002F';\n    return null;\n  },\n  routes: [\n    GoRoute(path: '\u002Flogin', builder: (_, __) => const LoginPage()),\n    ShellRoute(\n      builder: (context, state, child) => AppShell(child: child),\n      routes: [\n        GoRoute(path: '\u002F', builder: (_, __) => const HomePage()),\n        GoRoute(\n          path: '\u002Fproducts\u002F:id',\n          builder: (context, state) =>\n              ProductDetailPage(id: state.pathParameters['id']!),\n        ),\n      ],\n    ),\n  ],\n);\n```\n\n***\n\n## 8. 使用 Dio 的 HTTP 请求\n\n```dart\nfinal dio = Dio(BaseOptions(\n  baseUrl: const String.fromEnvironment('API_URL'),\n  connectTimeout: const Duration(seconds: 10),\n  receiveTimeout: const Duration(seconds: 30),\n  headers: {'Content-Type': 'application\u002Fjson'},\n));\n\n\u002F\u002F Add auth interceptor\ndio.interceptors.add(InterceptorsWrapper(\n  onRequest: (options, handler) async {\n    final token = await secureStorage.read(key: 'auth_token');\n    if (token != null) options.headers['Authorization'] = 'Bearer $token';\n    handler.next(options);\n  },\n  onError: (error, handler) async {\n    \u002F\u002F Guard against infinite retry loops: only attempt refresh once per request\n    final isRetry = error.requestOptions.extra['_isRetry'] == true;\n    if (!isRetry && error.response?.statusCode == 401) {\n      final refreshed = await attemptTokenRefresh();\n      if (refreshed) {\n        error.requestOptions.extra['_isRetry'] = true;\n        return handler.resolve(await dio.fetch(error.requestOptions));\n      }\n    }\n    handler.next(error);\n  },\n));\n\n\u002F\u002F Repository using Dio\nclass UserApiDataSource {\n  const UserApiDataSource(this._dio);\n  final Dio _dio;\n\n  Future\u003CUser> getById(String id) async {\n    final response = await _dio.get\u003CMap\u003CString, dynamic>>('\u002Fusers\u002F$id');\n    return User.fromJson(response.data!);\n  }\n}\n```\n\n***\n\n## 9. 错误处理架构\n\n```dart\n\u002F\u002F Global error capture — set up in main()\nvoid main() {\n  FlutterError.onError = (details) {\n    FlutterError.presentError(details);\n    crashlytics.recordFlutterFatalError(details);\n  };\n\n  PlatformDispatcher.instance.onError = (error, stack) {\n    crashlytics.recordError(error, stack, fatal: true);\n    return true;\n  };\n\n  runApp(const App());\n}\n\n\u002F\u002F Custom ErrorWidget for production\nclass App extends StatelessWidget {\n  @override\n  Widget build(BuildContext context) {\n    ErrorWidget.builder = (details) => ProductionErrorWidget(details);\n    return MaterialApp.router(routerConfig: router);\n  }\n}\n```\n\n***\n\n## 10. 测试快速参考\n\n```dart\n\u002F\u002F Unit test — use case\ntest('GetUserUseCase returns null for missing user', () async {\n  final repo = FakeUserRepository();\n  final useCase = GetUserUseCase(repo);\n  expect(await useCase('missing-id'), isNull);\n});\n\n\u002F\u002F BLoC test\nblocTest\u003CAuthCubit, AuthState>(\n  'emits loading then error on failed login',\n  build: () => AuthCubit(FakeAuthService(throwsOn: 'login')),\n  act: (cubit) => cubit.login('user@test.com', 'wrong'),\n  expect: () => [const AuthState.loading(), isA\u003CAuthError>()],\n);\n\n\u002F\u002F Widget test\ntestWidgets('CartBadge shows item count', (tester) async {\n  await tester.pumpWidget(\n    ProviderScope(\n      overrides: [cartNotifierProvider.overrideWith(() => FakeCartNotifier(count: 3))],\n      child: const MaterialApp(home: CartBadge()),\n    ),\n  );\n  expect(find.text('3'), findsOneWidget);\n});\n```\n\n***\n\n## 参考\n\n* [Effective Dart: 设计](https:\u002F\u002Fdart.dev\u002Feffective-dart\u002Fdesign)\n* [Flutter 性能最佳实践](https:\u002F\u002Fdocs.flutter.dev\u002Fperf\u002Fbest-practices)\n* [Riverpod 文档](https:\u002F\u002Friverpod.dev\u002F)\n* [BLoC 库](https:\u002F\u002Fbloclibrary.dev\u002F)\n* [GoRouter](https:\u002F\u002Fpub.dev\u002Fpackages\u002Fgo_router)\n* [Freezed](https:\u002F\u002Fpub.dev\u002Fpackages\u002Ffreezed)\n* 技能：`flutter-dart-code-review` — 全面审查清单\n* 规则：`rules\u002Fdart\u002F` — 编码风格、模式、安全性、测试、钩子\n","# Dart\u002FFlutter 模式\n\n## 使用场景\n\n在以下情况使用此技能：\n\n* 开始新的 Flutter 功能，需要状态管理、导航或数据访问的惯用模式\n* 审查或编写 Dart 代码，需要空安全、密封类型或异步组合的指导\n* 搭建新的 Flutter 项目，在 BLoC、Riverpod 或 Provider 之间做选择\n* 实现安全的 HTTP 客户端、WebView 集成或本地存储\n* 为 Flutter 组件、Cubit 或 Riverpod 提供者编写测试\n* 使用认证守卫配置 GoRouter\n\n## 工作原理\n\n此技能提供按关注点组织的、可直接复制粘贴的 Dart\u002FFlutter 代码模式：\n\n1. **空安全** — 避免 `!`，优先使用 `?.`\u002F`??`\u002F模式匹配\n2. **不可变状态** — 密封类、`freezed`、`copyWith`\n3. **异步组合** — 并发 `Future.wait`、`BuildContext` 后安全使用 `await`\n4. **组件架构** — 提取为类（而非方法）、`const` 传播、作用域重建\n5. **状态管理** — BLoC\u002FCubit 事件、Riverpod 通知器和派生提供者\n6. **导航** — 通过 `refreshListenable` 实现带响应式认证守卫的 GoRouter\n7. **网络请求** — 带拦截器的 Dio、带一次性重试守卫的令牌刷新\n8. **错误处理** — 全局捕获、`ErrorWidget.builder`、Crashlytics 集成\n9. **测试** — 单元测试（BLoC 测试）、组件测试（ProviderScope 覆盖）、使用假对象而非模拟对象\n\n## 示例\n\n```dart\n\u002F\u002F Sealed state — prevents impossible states\nsealed class AsyncState\u003CT> {}\nfinal class Loading\u003CT> extends AsyncState\u003CT> {}\nfinal class Success\u003CT> extends AsyncState\u003CT> { final T data; const Success(this.data); }\nfinal class Failure\u003CT> extends AsyncState\u003CT> { final Object error; const Failure(this.error); }\n\n\u002F\u002F GoRouter with reactive auth redirect\nfinal router = GoRouter(\n  refreshListenable: GoRouterRefreshStream(authCubit.stream),\n  redirect: (context, state) {\n    final authed = context.read\u003CAuthCubit>().state is AuthAuthenticated;\n    if (!authed && !state.matchedLocation.startsWith('\u002Flogin')) return '\u002Flogin';\n    return null;\n  },\n  routes: [...],\n);\n\n\u002F\u002F Riverpod derived provider with safe firstWhereOrNull\n@riverpod\ndouble cartTotal(Ref ref) {\n  final cart = ref.watch(cartNotifierProvider);\n  final products = ref.watch(productsProvider).valueOrNull ?? [];\n  return cart.fold(0.0, (total, item) {\n    final product = products.firstWhereOrNull((p) => p.id == item.productId);\n    return total + (product?.price ?? 0) * item.quantity;\n  });\n}\n```\n\n***\n\n适用于 Dart 和 Flutter 应用程序的实用、生产就绪模式。尽可能保持库无关性，并明确覆盖最常见的生态系统包。\n\n***\n\n## 1. 空安全基础\n\n### 优先使用模式而非感叹号操作符\n\n```dart\n\u002F\u002F BAD — crashes at runtime if null\nfinal name = user!.name;\n\n\u002F\u002F GOOD — provide fallback\nfinal name = user?.name ?? 'Unknown';\n\n\u002F\u002F GOOD — Dart 3 pattern matching (preferred for complex cases)\nfinal display = switch (user) {\n  User(:final name, :final email) => '$name \u003C$email>',\n  null => 'Guest',\n};\n\n\u002F\u002F GOOD — guard early return\nString getUserName(User? user) {\n  if (user == null) return 'Unknown';\n  return user.name; \u002F\u002F promoted to non-null after check\n}\n```\n\n### 避免过度使用 `late`\n\n```dart\n\u002F\u002F BAD — defers null error to runtime\nlate String userId;\n\n\u002F\u002F GOOD — nullable with explicit initialization\nString? userId;\n\n\u002F\u002F OK — use late only when initialization is guaranteed before first access\n\u002F\u002F (e.g., in initState() before any widget interaction)\nlate final AnimationController _controller;\n\n@override\nvoid initState() {\n  super.initState();\n  _controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 300));\n}\n```\n\n***\n\n## 2. 不可变状态\n\n### 状态层次结构的密封类\n\n```dart\nsealed class UserState {}\n\nfinal class UserInitial extends UserState {}\n\nfinal class UserLoading extends UserState {}\n\nfinal class UserLoaded extends UserState {\n  const UserLoaded(this.user);\n  final User user;\n}\n\nfinal class UserError extends UserState {\n  const UserError(this.message);\n  final String message;\n}\n\n\u002F\u002F Exhaustive switch — compiler enforces all branches\nWidget buildFrom(UserState state) => switch (state) {\n  UserInitial() => const SizedBox.shrink(),\n  UserLoading() => const CircularProgressIndicator(),\n  UserLoaded(:final user) => UserCard(user: user),\n  UserError(:final message) => ErrorText(message),\n};\n```\n\n### 使用 Freezed 实现无模板代码的不可变性\n\n```dart\nimport 'package:freezed_annotation\u002Ffreezed_annotation.dart';\n\npart 'user.freezed.dart';\npart 'user.g.dart';\n\n@freezed\nclass User with _$User {\n  const factory User({\n    required String id,\n    required String name,\n    required String email,\n    @Default(false) bool isAdmin,\n  }) = _User;\n\n  factory User.fromJson(Map\u003CString, dynamic> json) => _$UserFromJson(json);\n}\n\n\u002F\u002F Usage\nfinal user = User(id: '1', name: 'Alice', email: 'alice@example.com');\nfinal updated = user.copyWith(name: 'Alice Smith'); \u002F\u002F immutable update\nfinal json = user.toJson();\nfinal fromJson = User.fromJson(json);\n```\n\n***\n\n## 3. 异步组合\n\n### 使用 Future.wait 的结构化并发\n\n```dart\nFuture\u003CDashboardData> loadDashboard(UserRepository users, OrderRepository orders) async {\n  \u002F\u002F Run concurrently — don't await sequentially\n  final (userList, orderList) = await (\n    users.getAll(),\n    orders.getRecent(),\n  ).wait; \u002F\u002F Dart 3 record destructuring + Future.wait extension\n\n  return DashboardData(users: userList, orders: orderList);\n}\n```\n\n### 流模式\n\n```dart\n\u002F\u002F Repository exposes reactive streams for live data\nStream\u003CList\u003CItem>> watchCartItems() => _db\n    .watchTable('cart_items')\n    .map((rows) => rows.map(Item.fromRow).toList());\n\n\u002F\u002F In widget layer — declarative, no manual subscription\nStreamBuilder\u003CList\u003CItem>>(\n  stream: cartRepository.watchCartItems(),\n  builder: (context, snapshot) => switch (snapshot) {\n    AsyncSnapshot(connectionState: ConnectionState.waiting) =>\n        const CircularProgressIndicator(),\n    AsyncSnapshot(:final error?) => ErrorWidget(error.toString()),\n    AsyncSnapshot(:final data?) => CartList(items: data),\n    _ => const SizedBox.shrink(),\n  },\n)\n```\n\n### Await 后的 BuildContext\n\n```dart\n\u002F\u002F CRITICAL — always check mounted after any await in StatefulWidget\nFuture\u003Cvoid> _handleSubmit() async {\n  setState(() => _isLoading = true);\n  try {\n    await authService.login(_email, _password);\n    if (!mounted) return; \u002F\u002F ← guard before using context\n    context.go('\u002Fhome');\n  } on AuthException catch (e) {\n    if (!mounted) return;\n    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(e.message)));\n  } finally {\n    if (mounted) setState(() => _isLoading = false);\n  }\n}\n```\n\n***\n\n## 4. 组件架构\n\n### 提取为类，而非方法\n\n```dart\n\u002F\u002F BAD — private method returning widget, prevents optimization\nWidget _buildHeader() {\n  return Container(\n    padding: const EdgeInsets.all(16),\n    child: Text(title, style: Theme.of(context).textTheme.headlineMedium),\n  );\n}\n\n\u002F\u002F GOOD — separate widget class, enables const, element reuse\nclass _PageHeader extends StatelessWidget {\n  const _PageHeader(this.title);\n  final String title;\n\n  @override\n  Widget build(BuildContext context) {\n    return Container(\n      padding: const EdgeInsets.all(16),\n      child: Text(title, style: Theme.of(context).textTheme.headlineMedium),\n    );\n  }\n}\n```\n\n### const 传播\n\n```dart\n\u002F\u002F BAD — new instances every rebuild\nchild: Padding(\n  padding: EdgeInsets.all(16.0),       \u002F\u002F not const\n  child: Icon(Icons.home, size: 24.0), \u002F\u002F not const\n)\n\n\u002F\u002F GOOD — const stops rebuild propagation\nchild: const Padding(\n  padding: EdgeInsets.all(16.0),\n  child: Icon(Icons.home, size: 24.0),\n)\n```\n\n### 作用域重建\n\n```dart\n\u002F\u002F BAD — entire page rebuilds on every counter change\nclass CounterPage extends ConsumerWidget {\n  @override\n  Widget build(BuildContext context, WidgetRef ref) {\n    final count = ref.watch(counterProvider); \u002F\u002F rebuilds everything\n    return Scaffold(\n      body: Column(children: [\n        const ExpensiveHeader(), \u002F\u002F unnecessarily rebuilt\n        Text('$count'),\n        const ExpensiveFooter(), \u002F\u002F unnecessarily rebuilt\n      ]),\n    );\n  }\n}\n\n\u002F\u002F GOOD — isolate the rebuilding part\nclass CounterPage extends StatelessWidget {\n  const CounterPage({super.key});\n\n  @override\n  Widget build(BuildContext context) {\n    return const Scaffold(\n      body: Column(children: [\n        ExpensiveHeader(),        \u002F\u002F never rebuilt (const)\n        _CounterDisplay(),        \u002F\u002F only this rebuilds\n        ExpensiveFooter(),        \u002F\u002F never rebuilt (const)\n      ]),\n    );\n  }\n}\n\nclass _CounterDisplay extends ConsumerWidget {\n  const _CounterDisplay();\n\n  @override\n  Widget build(BuildContext context, WidgetRef ref) {\n    final count = ref.watch(counterProvider);\n    return Text('$count');\n  }\n}\n```\n\n***\n\n## 5. 状态管理：BLoC\u002FCubit\n\n```dart\n\u002F\u002F Cubit — synchronous or simple async state\nclass AuthCubit extends Cubit\u003CAuthState> {\n  AuthCubit(this._authService) : super(const AuthState.initial());\n  final AuthService _authService;\n\n  Future\u003Cvoid> login(String email, String password) async {\n    emit(const AuthState.loading());\n    try {\n      final user = await _authService.login(email, password);\n      emit(AuthState.authenticated(user));\n    } on AuthException catch (e) {\n      emit(AuthState.error(e.message));\n    }\n  }\n\n  void logout() {\n    _authService.logout();\n    emit(const AuthState.initial());\n  }\n}\n\n\u002F\u002F In widget\nBlocBuilder\u003CAuthCubit, AuthState>(\n  builder: (context, state) => switch (state) {\n    AuthInitial() => const LoginForm(),\n    AuthLoading() => const CircularProgressIndicator(),\n    AuthAuthenticated(:final user) => HomePage(user: user),\n    AuthError(:final message) => ErrorView(message: message),\n  },\n)\n```\n\n***\n\n## 6. 状态管理：Riverpod\n\n```dart\n\u002F\u002F Auto-dispose async provider\n@riverpod\nFuture\u003CList\u003CProduct>> products(Ref ref) async {\n  final repo = ref.watch(productRepositoryProvider);\n  return repo.getAll();\n}\n\n\u002F\u002F Notifier with complex mutations\n@riverpod\nclass CartNotifier extends _$CartNotifier {\n  @override\n  List\u003CCartItem> build() => [];\n\n  void add(Product product) {\n    final existing = state.where((i) => i.productId == product.id).firstOrNull;\n    if (existing != null) {\n      state = [\n        for (final item in state)\n          if (item.productId == product.id) item.copyWith(quantity: item.quantity + 1)\n          else item,\n      ];\n    } else {\n      state = [...state, CartItem(productId: product.id, quantity: 1)];\n    }\n  }\n\n  void remove(String productId) =>\n      state = state.where((i) => i.productId != productId).toList();\n\n  void clear() => state = [];\n}\n\n\u002F\u002F Derived provider (selector pattern)\n@riverpod\nint cartCount(Ref ref) => ref.watch(cartNotifierProvider).length;\n\n@riverpod\ndouble cartTotal(Ref ref) {\n  final cart = ref.watch(cartNotifierProvider);\n  final products = ref.watch(productsProvider).valueOrNull ?? [];\n  return cart.fold(0.0, (total, item) {\n    \u002F\u002F firstWhereOrNull (from collection package) avoids StateError when product is missing\n    final product = products.firstWhereOrNull((p) => p.id == item.productId);\n    return total + (product?.price ?? 0) * item.quantity;\n  });\n}\n```\n\n***\n\n## 7. 使用 GoRouter 的导航\n\n```dart\nfinal router = GoRouter(\n  initialLocation: '\u002F',\n  \u002F\u002F refreshListenable re-evaluates redirect whenever auth state changes\n  refreshListenable: GoRouterRefreshStream(authCubit.stream),\n  redirect: (context, state) {\n    final isLoggedIn = context.read\u003CAuthCubit>().state is AuthAuthenticated;\n    final isGoingToLogin = state.matchedLocation == '\u002Flogin';\n    if (!isLoggedIn && !isGoingToLogin) return '\u002Flogin';\n    if (isLoggedIn && isGoingToLogin) return '\u002F';\n    return null;\n  },\n  routes: [\n    GoRoute(path: '\u002Flogin', builder: (_, __) => const LoginPage()),\n    ShellRoute(\n      builder: (context, state, child) => AppShell(child: child),\n      routes: [\n        GoRoute(path: '\u002F', builder: (_, __) => const HomePage()),\n        GoRoute(\n          path: '\u002Fproducts\u002F:id',\n          builder: (context, state) =>\n              ProductDetailPage(id: state.pathParameters['id']!),\n        ),\n      ],\n    ),\n  ],\n);\n```\n\n***\n\n## 8. 使用 Dio 的 HTTP 请求\n\n```dart\nfinal dio = Dio(BaseOptions(\n  baseUrl: const String.fromEnvironment('API_URL'),\n  connectTimeout: const Duration(seconds: 10),\n  receiveTimeout: const Duration(seconds: 30),\n  headers: {'Content-Type': 'application\u002Fjson'},\n));\n\n\u002F\u002F Add auth interceptor\ndio.interceptors.add(InterceptorsWrapper(\n  onRequest: (options, handler) async {\n    final token = await secureStorage.read(key: 'auth_token');\n    if (token != null) options.headers['Authorization'] = 'Bearer $token';\n    handler.next(options);\n  },\n  onError: (error, handler) async {\n    \u002F\u002F Guard against infinite retry loops: only attempt refresh once per request\n    final isRetry = error.requestOptions.extra['_isRetry'] == true;\n    if (!isRetry && error.response?.statusCode == 401) {\n      final refreshed = await attemptTokenRefresh();\n      if (refreshed) {\n        error.requestOptions.extra['_isRetry'] = true;\n        return handler.resolve(await dio.fetch(error.requestOptions));\n      }\n    }\n    handler.next(error);\n  },\n));\n\n\u002F\u002F Repository using Dio\nclass UserApiDataSource {\n  const UserApiDataSource(this._dio);\n  final Dio _dio;\n\n  Future\u003CUser> getById(String id) async {\n    final response = await _dio.get\u003CMap\u003CString, dynamic>>('\u002Fusers\u002F$id');\n    return User.fromJson(response.data!);\n  }\n}\n```\n\n***\n\n## 9. 错误处理架构\n\n```dart\n\u002F\u002F Global error capture — set up in main()\nvoid main() {\n  FlutterError.onError = (details) {\n    FlutterError.presentError(details);\n    crashlytics.recordFlutterFatalError(details);\n  };\n\n  PlatformDispatcher.instance.onError = (error, stack) {\n    crashlytics.recordError(error, stack, fatal: true);\n    return true;\n  };\n\n  runApp(const App());\n}\n\n\u002F\u002F Custom ErrorWidget for production\nclass App extends StatelessWidget {\n  @override\n  Widget build(BuildContext context) {\n    ErrorWidget.builder = (details) => ProductionErrorWidget(details);\n    return MaterialApp.router(routerConfig: router);\n  }\n}\n```\n\n***\n\n## 10. 测试快速参考\n\n```dart\n\u002F\u002F Unit test — use case\ntest('GetUserUseCase returns null for missing user', () async {\n  final repo = FakeUserRepository();\n  final useCase = GetUserUseCase(repo);\n  expect(await useCase('missing-id'), isNull);\n});\n\n\u002F\u002F BLoC test\nblocTest\u003CAuthCubit, AuthState>(\n  'emits loading then error on failed login',\n  build: () => AuthCubit(FakeAuthService(throwsOn: 'login')),\n  act: (cubit) => cubit.login('user@test.com', 'wrong'),\n  expect: () => [const AuthState.loading(), isA\u003CAuthError>()],\n);\n\n\u002F\u002F Widget test\ntestWidgets('CartBadge shows item count', (tester) async {\n  await tester.pumpWidget(\n    ProviderScope(\n      overrides: [cartNotifierProvider.overrideWith(() => FakeCartNotifier(count: 3))],\n      child: const MaterialApp(home: CartBadge()),\n    ),\n  );\n  expect(find.text('3'), findsOneWidget);\n});\n```\n\n***\n\n## 参考\n\n* [Effective Dart: 设计](https:\u002F\u002Fdart.dev\u002Feffective-dart\u002Fdesign)\n* [Flutter 性能最佳实践](https:\u002F\u002Fdocs.flutter.dev\u002Fperf\u002Fbest-practices)\n* [Riverpod 文档](https:\u002F\u002Friverpod.dev\u002F)\n* [BLoC 库](https:\u002F\u002Fbloclibrary.dev\u002F)\n* [GoRouter](https:\u002F\u002Fpub.dev\u002Fpackages\u002Fgo_router)\n* [Freezed](https:\u002F\u002Fpub.dev\u002Fpackages\u002Ffreezed)\n* 技能：`flutter-dart-code-review` — 全面审查清单\n* 规则：`rules\u002Fdart\u002F` — 编码风格、模式、安全性、测试、钩子\n",{"name":5,"origin":24,"description":7},"ECC","main","57e7aa6b6e03bce1a7d7862ba9c2ec312f7f19b5","src\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fdocs\u002Fzh-CN\u002Fskills\u002Fdart-flutter-patterns",0,"https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee","https:\u002F\u002Fwithcyril.me\u002F","Hi, I’m Julian Cyril D, a Computer Science and Business Systems student at PSNACET.\r\nI’m passionate about full-stack development, UI\u002FUX design, and building sma","2026-11-04 23:28:50",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add Cyrilthetecchieee\u002Fcyril-code- --skill dart-flutter-patterns",{"tool":40,"command":41},"bunx","bunx skills add Cyrilthetecchieee\u002Fcyril-code- --skill dart-flutter-patterns",{"tool":43,"command":44},"pnpm","pnpm dlx skills add Cyrilthetecchieee\u002Fcyril-code- --skill dart-flutter-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fdocs\u002Fzh-CN\u002Fskills\u002Fdart-flutter-patterns\u002FSKILL.md",true,[],[49,58,65,73,80,87],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":54,"sourceHtmlUrl":55,"categories":56,"keywords":57,"publishedAt":19},"01M7AQV6CYX8RMC78420V9WZ62","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":19},"01M7AQV2895N3S1MEX6K76G6G2","youtube-downloader","Download YouTube videos with customizable quality and format options. Use this skill when the user asks to download, save, or grab YouTube videos. Supports various quality settings (best, 1080p, 720p, 480p, 360p), multiple formats (mp4, webm, mkv), and audio-only downloads as MP3.","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fvideo-downloader\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":69,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M7AQTRNX62DNKVZ5GXEHRBKB","theme-factory","Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with colors\u002Ffonts that you can apply to any artifact that has been creating, or can generate a new theme on-the-fly.","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftheme-factory\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftheme-factory\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M7AQTNNVHAAN9H6DA8T6ZVE0","template-skill","Replace with description of the skill and when Claude should use it.","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftemplate-skill\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M7AQTJ3MQ6AKX152MEX2MYCC","tailored-resume-generator","Analyzes job descriptions and generates tailored resumes that highlight relevant experience, skills, and achievements to maximize interview chances","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftailored-resume-generator\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":91,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M7AQTD7D5MYET2YWG7HG9WM3","slack-gif-creator","Toolkit for creating animated GIFs optimized for Slack, with validators for size constraints and composable animation primitives. This skill applies when users request animated GIFs or emoji animations for Slack from descriptions like \"make me a GIF for Slack of X doing Y\".","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fslack-gif-creator\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fslack-gif-creator\u002FSKILL.md",[],[]]