{"slug":"dart-flutter-patterns","title":"dart-flutter-patterns","summary":"Production-ready Dart and Flutter patterns covering null safety, immutable state with Freezed, async composition, widget architecture, state management (BLoC, Riverpod, Provider), GoRouter navigation with auth guards, Dio networking, error handling, and testing. Use when writing ","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-12-02T16:53:32.565094Z","repo":{"url":"https://github.com/beginwithu/agent-skills","stars":11,"forks":2,"license":"MIT","updatedAt":"2026-12-02T16:37:11Z"},"bodyHtml":"<hr>\n<h2>name: dart-flutter-patterns\ndescription: Production-ready Dart and Flutter patterns covering null safety, immutable state with Freezed, async composition, widget architecture, state management (BLoC, Riverpod, Provider), GoRouter navigation with auth guards, Dio networking, error handling, and testing. Use when writing or reviewing Dart and Flutter code — state, widgets, navigation, networking, or architecture.\nmetadata:\norigin: ECC</h2>\n<h1>Dart/Flutter Patterns</h1>\n<h2>When to Use</h2>\n<p>Use this skill when:</p>\n<ul>\n<li>Starting a new Flutter feature and need idiomatic patterns for state management, navigation, or data access</li>\n<li>Reviewing or writing Dart code and need guidance on null safety, sealed types, or async composition</li>\n<li>Setting up a new Flutter project and choosing between BLoC, Riverpod, or Provider</li>\n<li>Implementing secure HTTP clients, WebView integration, or local storage</li>\n<li>Writing tests for Flutter widgets, Cubits, or Riverpod providers</li>\n<li>Wiring up GoRouter with authentication guards</li>\n</ul>\n<h2>How It Works</h2>\n<p>This skill provides copy-paste-ready Dart/Flutter code patterns organized by concern:</p>\n<ol>\n<li><strong>Null safety</strong> — avoid <code>!</code>, prefer <code>?.</code>/<code>??</code>/pattern matching</li>\n<li><strong>Immutable state</strong> — sealed classes, <code>freezed</code>, <code>copyWith</code></li>\n<li><strong>Async composition</strong> — concurrent <code>Future.wait</code>, safe <code>BuildContext</code> after <code>await</code></li>\n<li><strong>Widget architecture</strong> — extract to classes (not methods), <code>const</code> propagation, scoped rebuilds</li>\n<li><strong>State management</strong> — BLoC/Cubit events, Riverpod notifiers and derived providers</li>\n<li><strong>Navigation</strong> — GoRouter with reactive auth guards via <code>refreshListenable</code></li>\n<li><strong>Networking</strong> — Dio with interceptors, token refresh with one-time retry guard</li>\n<li><strong>Error handling</strong> — global capture, <code>ErrorWidget.builder</code>, crashlytics wiring</li>\n<li><strong>Testing</strong> — unit (BLoC test), widget (ProviderScope overrides), fakes over mocks</li>\n</ol>\n<h2>Examples</h2>\n<pre><code>// Sealed state — prevents impossible states\nsealed class AsyncState&lt;T&gt; {}\nfinal class Loading&lt;T&gt; extends AsyncState&lt;T&gt; {}\nfinal class Success&lt;T&gt; extends AsyncState&lt;T&gt; { final T data; const Success(this.data); }\nfinal class Failure&lt;T&gt; extends AsyncState&lt;T&gt; { final Object error; const Failure(this.error); }\n\n// GoRouter with reactive auth redirect\nfinal router = GoRouter(\n  refreshListenable: GoRouterRefreshStream(authCubit.stream),\n  redirect: (context, state) {\n    final authed = context.read&lt;AuthCubit&gt;().state is AuthAuthenticated;\n    if (!authed &amp;&amp; !state.matchedLocation.startsWith('/login')) return '/login';\n    return null;\n  },\n  routes: [...],\n);\n\n// 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) =&gt; p.id == item.productId);\n    return total + (product?.price ?? 0) * item.quantity;\n  });\n}\n</code></pre>\n<hr>\n<p>Practical, production-ready patterns for Dart and Flutter applications. Library-agnostic where possible, with explicit coverage of the most common ecosystem packages.</p>\n<hr>\n<h2>1. Null Safety Fundamentals</h2>\n<h3>Prefer Patterns Over Bang Operator</h3>\n<pre><code>// BAD — crashes at runtime if null\nfinal name = user!.name;\n\n// GOOD — provide fallback\nfinal name = user?.name ?? 'Unknown';\n\n// GOOD — Dart 3 pattern matching (preferred for complex cases)\nfinal display = switch (user) {\n  User(:final name, :final email) =&gt; '$name &lt;$email&gt;',\n  null =&gt; 'Guest',\n};\n\n// GOOD — guard early return\nString getUserName(User? user) {\n  if (user == null) return 'Unknown';\n  return user.name; // promoted to non-null after check\n}\n</code></pre>\n<h3>Avoid <code>late</code> Overuse</h3>\n<pre><code>// BAD — defers null error to runtime\nlate String userId;\n\n// GOOD — nullable with explicit initialization\nString? userId;\n\n// OK — use late only when initialization is guaranteed before first access\n// (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</code></pre>\n<hr>\n<h2>2. Immutable State</h2>\n<h3>Sealed Classes for State Hierarchies</h3>\n<pre><code>sealed 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// Exhaustive switch — compiler enforces all branches\nWidget buildFrom(UserState state) =&gt; switch (state) {\n  UserInitial() =&gt; const SizedBox.shrink(),\n  UserLoading() =&gt; const CircularProgressIndicator(),\n  UserLoaded(:final user) =&gt; UserCard(user: user),\n  UserError(:final message) =&gt; ErrorText(message),\n};\n</code></pre>\n<h3>Freezed for Boilerplate-Free Immutability</h3>\n<pre><code>import 'package:freezed_annotation/freezed_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&lt;String, dynamic&gt; json) =&gt; _$UserFromJson(json);\n}\n\n// Usage\nfinal user = User(id: '1', name: 'Alice', email: 'alice@example.com');\nfinal updated = user.copyWith(name: 'Alice Smith'); // immutable update\nfinal json = user.toJson();\nfinal fromJson = User.fromJson(json);\n</code></pre>\n<hr>\n<h2>3. Async Composition</h2>\n<h3>Structured Concurrency with Future.wait</h3>\n<pre><code>Future&lt;DashboardData&gt; loadDashboard(UserRepository users, OrderRepository orders) async {\n  // Run concurrently — don't await sequentially\n  final (userList, orderList) = await (\n    users.getAll(),\n    orders.getRecent(),\n  ).wait; // Dart 3 record destructuring + Future.wait extension\n\n  return DashboardData(users: userList, orders: orderList);\n}\n</code></pre>\n<h3>Stream Patterns</h3>\n<pre><code>// Repository exposes reactive streams for live data\nStream&lt;List&lt;Item&gt;&gt; watchCartItems() =&gt; _db\n    .watchTable('cart_items')\n    .map((rows) =&gt; rows.map(Item.fromRow).toList());\n\n// In widget layer — declarative, no manual subscription\nStreamBuilder&lt;List&lt;Item&gt;&gt;(\n  stream: cartRepository.watchCartItems(),\n  builder: (context, snapshot) =&gt; switch (snapshot) {\n    AsyncSnapshot(connectionState: ConnectionState.waiting) =&gt;\n        const CircularProgressIndicator(),\n    AsyncSnapshot(:final error?) =&gt; ErrorWidget(error.toString()),\n    AsyncSnapshot(:final data?) =&gt; CartList(items: data),\n    _ =&gt; const SizedBox.shrink(),\n  },\n)\n</code></pre>\n<h3>BuildContext After Await</h3>\n<pre><code>// CRITICAL — always check mounted after any await in StatefulWidget\nFuture&lt;void&gt; _handleSubmit() async {\n  setState(() =&gt; _isLoading = true);\n  try {\n    await authService.login(_email, _password);\n    if (!mounted) return; // ← guard before using context\n    context.go('/home');\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(() =&gt; _isLoading = false);\n  }\n}\n</code></pre>\n<hr>\n<h2>4. Widget Architecture</h2>\n<h3>Extract to Classes, Not Methods</h3>\n<pre><code>// 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// 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</code></pre>\n<h3>const Propagation</h3>\n<pre><code>// BAD — new instances every rebuild\nchild: Padding(\n  padding: EdgeInsets.all(16.0),       // not const\n  child: Icon(Icons.home, size: 24.0), // not const\n)\n\n// GOOD — const stops rebuild propagation\nchild: const Padding(\n  padding: EdgeInsets.all(16.0),\n  child: Icon(Icons.home, size: 24.0),\n)\n</code></pre>\n<h3>Scoped Rebuilds</h3>\n<pre><code>// 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); // rebuilds everything\n    return Scaffold(\n      body: Column(children: [\n        const ExpensiveHeader(), // unnecessarily rebuilt\n        Text('$count'),\n        const ExpensiveFooter(), // unnecessarily rebuilt\n      ]),\n    );\n  }\n}\n\n// 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(),        // never rebuilt (const)\n        _CounterDisplay(),        // only this rebuilds\n        ExpensiveFooter(),        // 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</code></pre>\n<hr>\n<h2>5. State Management: BLoC/Cubit</h2>\n<pre><code>// Cubit — synchronous or simple async state\nclass AuthCubit extends Cubit&lt;AuthState&gt; {\n  AuthCubit(this._authService) : super(const AuthState.initial());\n  final AuthService _authService;\n\n  Future&lt;void&gt; 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// In widget\nBlocBuilder&lt;AuthCubit, AuthState&gt;(\n  builder: (context, state) =&gt; switch (state) {\n    AuthInitial() =&gt; const LoginForm(),\n    AuthLoading() =&gt; const CircularProgressIndicator(),\n    AuthAuthenticated(:final user) =&gt; HomePage(user: user),\n    AuthError(:final message) =&gt; ErrorView(message: message),\n  },\n)\n</code></pre>\n<hr>\n<h2>6. State Management: Riverpod</h2>\n<pre><code>// Auto-dispose async provider\n@riverpod\nFuture&lt;List&lt;Product&gt;&gt; products(Ref ref) async {\n  final repo = ref.watch(productRepositoryProvider);\n  return repo.getAll();\n}\n\n// Notifier with complex mutations\n@riverpod\nclass CartNotifier extends _$CartNotifier {\n  @override\n  List&lt;CartItem&gt; build() =&gt; [];\n\n  void add(Product product) {\n    final existing = state.where((i) =&gt; 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) =&gt;\n      state = state.where((i) =&gt; i.productId != productId).toList();\n\n  void clear() =&gt; state = [];\n}\n\n// Derived provider (selector pattern)\n@riverpod\nint cartCount(Ref ref) =&gt; 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    // firstWhereOrNull (from collection package) avoids StateError when product is missing\n    final product = products.firstWhereOrNull((p) =&gt; p.id == item.productId);\n    return total + (product?.price ?? 0) * item.quantity;\n  });\n}\n</code></pre>\n<hr>\n<h2>7. Navigation with GoRouter</h2>\n<pre><code>final router = GoRouter(\n  initialLocation: '/',\n  // refreshListenable re-evaluates redirect whenever auth state changes\n  refreshListenable: GoRouterRefreshStream(authCubit.stream),\n  redirect: (context, state) {\n    final isLoggedIn = context.read&lt;AuthCubit&gt;().state is AuthAuthenticated;\n    final isGoingToLogin = state.matchedLocation == '/login';\n    if (!isLoggedIn &amp;&amp; !isGoingToLogin) return '/login';\n    if (isLoggedIn &amp;&amp; isGoingToLogin) return '/';\n    return null;\n  },\n  routes: [\n    GoRoute(path: '/login', builder: (_, __) =&gt; const LoginPage()),\n    ShellRoute(\n      builder: (context, state, child) =&gt; AppShell(child: child),\n      routes: [\n        GoRoute(path: '/', builder: (_, __) =&gt; const HomePage()),\n        GoRoute(\n          path: '/products/:id',\n          builder: (context, state) =&gt;\n              ProductDetailPage(id: state.pathParameters['id']!),\n        ),\n      ],\n    ),\n  ],\n);\n</code></pre>\n<hr>\n<h2>8. HTTP with Dio</h2>\n<pre><code>final 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/json'},\n));\n\n// 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    // Guard against infinite retry loops: only attempt refresh once per request\n    final isRetry = error.requestOptions.extra['_isRetry'] == true;\n    if (!isRetry &amp;&amp; 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// Repository using Dio\nclass UserApiDataSource {\n  const UserApiDataSource(this._dio);\n  final Dio _dio;\n\n  Future&lt;User&gt; getById(String id) async {\n    final response = await _dio.get&lt;Map&lt;String, dynamic&gt;&gt;('/users/$id');\n    return User.fromJson(response.data!);\n  }\n}\n</code></pre>\n<hr>\n<h2>9. Error Handling Architecture</h2>\n<pre><code>// 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// Custom ErrorWidget for production\nclass App extends StatelessWidget {\n  @override\n  Widget build(BuildContext context) {\n    ErrorWidget.builder = (details) =&gt; ProductionErrorWidget(details);\n    return MaterialApp.router(routerConfig: router);\n  }\n}\n</code></pre>\n<hr>\n<h2>10. Testing Quick Reference</h2>\n<pre><code>// 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// BLoC test\nblocTest&lt;AuthCubit, AuthState&gt;(\n  'emits loading then error on failed login',\n  build: () =&gt; AuthCubit(FakeAuthService(throwsOn: 'login')),\n  act: (cubit) =&gt; cubit.login('user@test.com', 'wrong'),\n  expect: () =&gt; [const AuthState.loading(), isA&lt;AuthError&gt;()],\n);\n\n// Widget test\ntestWidgets('CartBadge shows item count', (tester) async {\n  await tester.pumpWidget(\n    ProviderScope(\n      overrides: [cartNotifierProvider.overrideWith(() =&gt; FakeCartNotifier(count: 3))],\n      child: const MaterialApp(home: CartBadge()),\n    ),\n  );\n  expect(find.text('3'), findsOneWidget);\n});\n</code></pre>\n<hr>\n<h2>References</h2>\n<ul>\n<li><a href=\"https://dart.dev/effective-dart/design\">Effective Dart: Design</a></li>\n<li><a href=\"https://docs.flutter.dev/perf/best-practices\">Flutter Performance Best Practices</a></li>\n<li><a href=\"https://riverpod.dev/\">Riverpod Documentation</a></li>\n<li><a href=\"https://bloclibrary.dev/\">BLoC Library</a></li>\n<li><a href=\"https://pub.dev/packages/go_router\">GoRouter</a></li>\n<li><a href=\"https://pub.dev/packages/freezed\">Freezed</a></li>\n<li>Skill: <code>flutter-dart-code-review</code> — comprehensive review checklist</li>\n<li>Rules: <code>rules/dart/</code> — coding style, patterns, security, testing, hooks</li>\n</ul>\n","files":[{"path":"LICENSE","sizeBytes":1071,"isText":false},{"path":"SKILL.md","sizeBytes":16024,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-12-02T16:56:15.61408Z","sha256":"BB3ED92EFDD076B9421587ABFB45F1EDAF846C7A7A42BC30AC986741B1DBCF65","sizeBytes":6622},"review":null,"source":{"repositoryUrl":"https://github.com/beginwithu/agent-skills","path":"skills/dart-flutter-patterns","license":"MIT","commit":"a960304c52212f2e845067047f5cefc0c594d787","subtreeSha":"E7C9E78A4843CAC3DC47A6ECC21197B6A098567979064F704A009FA948AF4718","lastSyncedAt":"2026-12-02T16:52:59.20206Z"},"reviewedAt":"2026-12-02T17:01:35.124179Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/beginwithu/agent-skills/tree/main/skills/dart-flutter-patterns"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install beginwithu-agent-skills@llmmart"},{"target":"git","command":"git clone https://github.com/beginwithu/agent-skills.git"}]}