[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6JCVGAAMCC1G8EY29WD2823":3,"skill-same:01M6JCVGAAMCC1G8EY29WD2823":66},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":47,"repositoryHtmlUrl":48,"repositoryHomepageUrl":49,"ownerHtmlUrl":50,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":51,"install":52,"resources":65},"01M6JCVGAAMCC1G8EY29WD2823","dart-flutter-patterns",null,"Production-ready Dart and Flutter patterns covering null safety, immutable state, async composition, widget architecture, popular state management frameworks (BLoC, Riverpod, Provider), GoRouter navigation, Dio networking, Freezed code generation, and clean architecture.","S3YED\u002Fappie-kit","S3YED","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F62743867?v=4","01M6JBKBRRVP6KMS0VWZ27T3R6","01M6JBKBX0KG30284PW1DBYJT1",14,"MIT","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fecc\u002Fdart-flutter-patterns\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"dart flutter patterns","patterns","dart","flutter","ready","production-ready","riverpod","frameworks","clean architecture","clean","provider","async","architecture","Composition","Safety","Code Generation","state","networking","code","state management","2026-11-10 10:12:30",false,"---\nname: dart-flutter-patterns\ndescription: Production-ready Dart and Flutter patterns covering null safety, immutable state, async composition, widget architecture, popular state management frameworks (BLoC, Riverpod, Provider), GoRouter navigation, Dio networking, Freezed code generation, and clean architecture.\norigin: ECC\n---\n\n# Dart\u002FFlutter Patterns\n\n## When to Use\n\nUse this skill when:\n- Starting a new Flutter feature and need idiomatic patterns for state management, navigation, or data access\n- Reviewing or writing Dart code and need guidance on null safety, sealed types, or async composition\n- Setting up a new Flutter project and choosing between BLoC, Riverpod, or Provider\n- Implementing secure HTTP clients, WebView integration, or local storage\n- Writing tests for Flutter widgets, Cubits, or Riverpod providers\n- Wiring up GoRouter with authentication guards\n\n## How It Works\n\nThis skill provides copy-paste-ready Dart\u002FFlutter code patterns organized by concern:\n1. **Null safety** — avoid `!`, prefer `?.`\u002F`??`\u002Fpattern matching\n2. **Immutable state** — sealed classes, `freezed`, `copyWith`\n3. **Async composition** — concurrent `Future.wait`, safe `BuildContext` after `await`\n4. **Widget architecture** — extract to classes (not methods), `const` propagation, scoped rebuilds\n5. **State management** — BLoC\u002FCubit events, Riverpod notifiers and derived providers\n6. **Navigation** — GoRouter with reactive auth guards via `refreshListenable`\n7. **Networking** — Dio with interceptors, token refresh with one-time retry guard\n8. **Error handling** — global capture, `ErrorWidget.builder`, crashlytics wiring\n9. **Testing** — unit (BLoC test), widget (ProviderScope overrides), fakes over mocks\n\n## Examples\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\nPractical, production-ready patterns for Dart and Flutter applications. Library-agnostic where possible, with explicit coverage of the most common ecosystem packages.\n\n---\n\n## 1. Null Safety Fundamentals\n\n### Prefer Patterns Over Bang Operator\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### Avoid `late` Overuse\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. Immutable State\n\n### Sealed Classes for State Hierarchies\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 for Boilerplate-Free Immutability\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. Async Composition\n\n### Structured Concurrency with 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### Stream Patterns\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### BuildContext After Await\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. Widget Architecture\n\n### Extract to Classes, Not Methods\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 Propagation\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### Scoped Rebuilds\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. State Management: 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. State Management: 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. Navigation with 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. HTTP with Dio\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. Error Handling Architecture\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. Testing Quick Reference\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## References\n\n- [Effective Dart: Design](https:\u002F\u002Fdart.dev\u002Feffective-dart\u002Fdesign)\n- [Flutter Performance Best Practices](https:\u002F\u002Fdocs.flutter.dev\u002Fperf\u002Fbest-practices)\n- [Riverpod Documentation](https:\u002F\u002Friverpod.dev\u002F)\n- [BLoC Library](https:\u002F\u002Fbloclibrary.dev\u002F)\n- [GoRouter](https:\u002F\u002Fpub.dev\u002Fpackages\u002Fgo_router)\n- [Freezed](https:\u002F\u002Fpub.dev\u002Fpackages\u002Ffreezed)\n- Skill: `flutter-dart-code-review` — comprehensive review checklist\n- Rules: `rules\u002Fdart\u002F` — coding style, patterns, security, testing, hooks\n","# Dart\u002FFlutter Patterns\n\n## When to Use\n\nUse this skill when:\n- Starting a new Flutter feature and need idiomatic patterns for state management, navigation, or data access\n- Reviewing or writing Dart code and need guidance on null safety, sealed types, or async composition\n- Setting up a new Flutter project and choosing between BLoC, Riverpod, or Provider\n- Implementing secure HTTP clients, WebView integration, or local storage\n- Writing tests for Flutter widgets, Cubits, or Riverpod providers\n- Wiring up GoRouter with authentication guards\n\n## How It Works\n\nThis skill provides copy-paste-ready Dart\u002FFlutter code patterns organized by concern:\n1. **Null safety** — avoid `!`, prefer `?.`\u002F`??`\u002Fpattern matching\n2. **Immutable state** — sealed classes, `freezed`, `copyWith`\n3. **Async composition** — concurrent `Future.wait`, safe `BuildContext` after `await`\n4. **Widget architecture** — extract to classes (not methods), `const` propagation, scoped rebuilds\n5. **State management** — BLoC\u002FCubit events, Riverpod notifiers and derived providers\n6. **Navigation** — GoRouter with reactive auth guards via `refreshListenable`\n7. **Networking** — Dio with interceptors, token refresh with one-time retry guard\n8. **Error handling** — global capture, `ErrorWidget.builder`, crashlytics wiring\n9. **Testing** — unit (BLoC test), widget (ProviderScope overrides), fakes over mocks\n\n## Examples\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\nPractical, production-ready patterns for Dart and Flutter applications. Library-agnostic where possible, with explicit coverage of the most common ecosystem packages.\n\n---\n\n## 1. Null Safety Fundamentals\n\n### Prefer Patterns Over Bang Operator\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### Avoid `late` Overuse\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. Immutable State\n\n### Sealed Classes for State Hierarchies\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 for Boilerplate-Free Immutability\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. Async Composition\n\n### Structured Concurrency with 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### Stream Patterns\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### BuildContext After Await\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. Widget Architecture\n\n### Extract to Classes, Not Methods\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 Propagation\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### Scoped Rebuilds\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. State Management: 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. State Management: 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. Navigation with 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. HTTP with Dio\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. Error Handling Architecture\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. Testing Quick Reference\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## References\n\n- [Effective Dart: Design](https:\u002F\u002Fdart.dev\u002Feffective-dart\u002Fdesign)\n- [Flutter Performance Best Practices](https:\u002F\u002Fdocs.flutter.dev\u002Fperf\u002Fbest-practices)\n- [Riverpod Documentation](https:\u002F\u002Friverpod.dev\u002F)\n- [BLoC Library](https:\u002F\u002Fbloclibrary.dev\u002F)\n- [GoRouter](https:\u002F\u002Fpub.dev\u002Fpackages\u002Fgo_router)\n- [Freezed](https:\u002F\u002Fpub.dev\u002Fpackages\u002Ffreezed)\n- Skill: `flutter-dart-code-review` — comprehensive review checklist\n- Rules: `rules\u002Fdart\u002F` — coding style, patterns, security, testing, hooks\n",{"name":5,"origin":43,"description":7},"ECC","master","8ec37df6d71fb664ea19d32c079e7d3ff931a8e0","skills\u002Fecc\u002Fdart-flutter-patterns",3,"https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit","https:\u002F\u002Fweblyfe.ai","https:\u002F\u002Fgithub.com\u002FS3YED","2026-08-27 01:54:02",{"source":8,"skillName":5,"commands":53,"prompt":63,"zipAvailable":64},[54,57,60],{"tool":55,"command":56},"npx","npx skills add S3YED\u002Fappie-kit --skill dart-flutter-patterns",{"tool":58,"command":59},"bunx","bunx skills add S3YED\u002Fappie-kit --skill dart-flutter-patterns",{"tool":61,"command":62},"pnpm","pnpm dlx skills add S3YED\u002Fappie-kit --skill dart-flutter-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fecc\u002Fdart-flutter-patterns\u002FSKILL.md",true,[],[67,103,138,164,195,219],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":84,"publishedAt":38},"01M6JFD4M6N4DSGC7TXEJ5R3J2","ai-music","AI music generation and audio tools: HeartMuLa lyrics-to-music generation, songwriting craft (+ Suno prompts), and audio spectrogram\u002Ffeature visualization.","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fwethlete\u002Fai-music\u002FSKILL.md",[73,78,81],{"categoryNo":74,"categoryName":75,"taxonomyType":76,"taxonomyTypeDesc":77},"01JBSEEDCAT000000000000013","分析与可视化","SCENARIO","使用场景",{"categoryNo":79,"categoryName":80,"taxonomyType":76,"taxonomyTypeDesc":77},"01JBSEEDCAT000000000000016","图像与多媒体",{"categoryNo":82,"categoryName":83,"taxonomyType":76,"taxonomyTypeDesc":77},"01JBSEEDCAT000000000000023","Skill与智能体开发",[85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102],"music","ai music","humanizer","visualization","Tools","Audio","hermes","hermes agent","songwriting","suno","lyrics","prompts","heartmula","craft","generation","feature","ai music generation","music generation",{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":117,"publishedAt":38},"01M6JFCZE4XNFQFMNZDHKHT5V5","agentic-webdesign-design-system-ingestion","Use v0 Design Systems 2.0, Bolt Design System Agents, or Lovable to generate production UI from a client's real design system components — not generic Tailwind. Use when building a client website where brand consistency matters.","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fweb-design\u002Fagentic-webdesign-design-system-ingestion\u002FSKILL.md",[109,112],{"categoryNo":110,"categoryName":111,"taxonomyType":76,"taxonomyTypeDesc":77},"01JBSEEDCAT000000000000015","视觉设计",{"categoryNo":113,"categoryName":114,"taxonomyType":115,"taxonomyTypeDesc":116},"01JBSEEDCAT000000000000032","设计师","PROFESSION","适用职业",[118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137],"design","agentic","design system","system","ingestion","webdesign","agentic webdesign design system ingestion","components","generate","design systems","website","ui","Tailwind","bolt","lovable","v0","design-system","wed","design system components","appie",{"skillNo":139,"name":140,"nameZh":6,"description":141,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":142,"categories":143,"keywords":146,"publishedAt":38},"01M6JFCVPX3913CFAS6QQJ33ZB","agentic-webdesign-agent-elements","Use 21st.dev Agent Elements — 25 shadcn\u002Fui components purpose-built for AI agent UIs. Tool cards (Bash, Edit, Search, Plan, Subagent, MCP), chat, input, streaming. Open source, shadcn-registry install, no runtime lock-in.","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fweb-design\u002Fagentic-webdesign-agent-elements\u002FSKILL.md",[144,145],{"categoryNo":82,"categoryName":83,"taxonomyType":76,"taxonomyTypeDesc":77},{"categoryNo":113,"categoryName":114,"taxonomyType":115,"taxonomyTypeDesc":116},[119,147,123,148,149,150,125,151,152,153,154,155,156,157,158,159,160,161,162,163],"elements","agentic webdesign agent elements","MCP","ai agent","registry","search","streaming","open source","open","Bash","plan","subagent","edit","install","input","lock","source",{"skillNo":165,"name":166,"nameZh":6,"description":167,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":168,"categories":169,"keywords":174,"publishedAt":38},"01M6JFCQC7H65M9QJ6TRE71BS1","vercel-deployment","Deploy static sites and frontends to Vercel — handles both CLI and REST API paths, including the CLI token sanitization workaround.","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fsoftware-development\u002Fvercel-deployment\u002FSKILL.md",[170,173],{"categoryNo":171,"categoryName":172,"taxonomyType":76,"taxonomyTypeDesc":77},"01JBSEEDCAT000000000000011","运维与部署",{"categoryNo":82,"categoryName":83,"taxonomyType":76,"taxonomyTypeDesc":77},[175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194],"deployment","vercel deployment","vercel","macos","cli","linux","windows","deploy","vercel deploy","REST","api","site","deploy to vercel","token","rest api","host","sites","paths","sanitization","static site",{"skillNo":196,"name":197,"nameZh":6,"description":198,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":199,"categories":200,"keywords":202,"publishedAt":38},"01M6JFCM4SMTXBM5A01BK2YQG1","software-quality-workflows","Umbrella workflow for TDD, debugging, code simplification, spikes, pre-commit review, and debugger-assisted investigation.","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fsoftware-development\u002Fsoftware-quality-workflows\u002FSKILL.md",[201],{"categoryNo":82,"categoryName":83,"taxonomyType":76,"taxonomyTypeDesc":77},[203,204,205,206,207,208,209,210,211,36,212,213,214,215,216,217,218],"workflows","quality","software","software quality workflows","review","tdd","workflow","commit","debugging","debugger","pre-commit","investigation","code simplification","user","simplification","for",{"skillNo":220,"name":221,"nameZh":6,"description":222,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":223,"categories":224,"keywords":232,"publishedAt":38},"01M6JFCGD0M6CEATY01W7YN6DB","react-component-refactoring","Safely refactor large React components into smaller, maintainable pieces using proven patterns","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fsoftware-development\u002Freact-component-refactoring\u002FSKILL.md",[225,228,231],{"categoryNo":226,"categoryName":227,"taxonomyType":76,"taxonomyTypeDesc":77},"01JBSEEDCAT000000000000007","代码审查",{"categoryNo":229,"categoryName":230,"taxonomyType":76,"taxonomyTypeDesc":77},"01JBSEEDCAT000000000000009","前端开发",{"categoryNo":82,"categoryName":83,"taxonomyType":76,"taxonomyTypeDesc":77},[233,234,235,236,237,238,239,240,178,241,242,125,243,181,244,36,245,246,19,247],"react","component","refactoring","component refactoring","react component","react component refactoring","frontend","writing","safe","typescript","react components","modular","refactor","simplify","test-driven-development"]