Skip to content

EliasOulkadi/shokunin / .pack/skills/flutter

flutter

Verified

Build production Flutter apps with Clean Architecture, Riverpod (preferred over Bloc/Provider), GoRouter navigation, Impeller rendering engine, Dart 3.7+ patterns, platform channels via Pigeon, and App Store/Play Store deployment.

Flutter Architect

Widgets are functions of state. Keep them pure. Compose, don't inherit.

Production Flutter apps with Clean Architecture, Riverpod, GoRouter, Impeller, and platform channels. Based on Flutter docs, Riverpod patterns, and production experience.

Decision Framework

Before writing Flutter code, answer:

  • Is native performance critical? (animations, camera, maps) → Flutter is a strong fit
  • Is the team already experienced with Dart? → Proceed. If React/TypeScript, consider react-native skill
  • Is the app content-heavy with standard platform UI? → Consider native or react-native
  • Does the app need platform-specific features not available in packages? → Verify pub.dev coverage first

Workflow

  1. Scaffold: dart run flutter_skeleton or create lib/core, lib/features/*/domain|data|presentation by hand. Add Riverpod + GoRouter + Freezed deps in pubspec.yaml.
  2. Domain first: Define entities, repository contracts, and use cases. Zero Flutter imports. Pure Dart with freezed for sealed unions.
  3. Data layer: Implement repositories with Dio/retrofit, DTOs with json_serializable, and data sources. Wire up in Riverpod with Provider<AuthRepository>.
  4. Presentation: Build screens and widgets with ConsumerWidget/ConsumerStatefulWidget. Wire NotifierProvider for each feature. Keep ref.watch at leaf level.
  5. Routing: Configure GoRouter with auth redirect (redirect guard), nested routes per feature, and deep link patterns.
  6. Ship: Run tests → flutter build appbundle / flutter build ipa → deploy via Codemagic or GitHub Actions. Enable Impeller on Android in build.gradle.

Sub-Commands

CommandDescription
scaffoldCreate project with folder structure and dependencies
featureDesign a feature with domain/data/presentation layers
stateSet up Riverpod providers for a feature
routeConfigure GoRouter with auth guard and deep links
testWrite unit + widget + integration tests
shipBuild and deploy to App Store + Play Store

Architecture

lib/
├ core/
│   ├ theme/      # Material 3 theming
│   ├ constants/  # App-wide constants
│   └ network/    # Dio + interceptors
├ features/
│  ├ auth/
│  │   ├ domain/        # Pure Dart — entities, use cases, contracts
│  │   ├ data/          # Repo impl, API, DTOs, data sources
│  │   └ presentation/  # Riverpod providers + screens + widgets
│  ├ home/
│  └ profile/
└ main.dart

Domain Layer (zero Flutter imports)

class User {
  final String id;
  final String email;
  const User({required this.id, required this.email});
}

abstract class AuthRepository {
  Future<User> login(String email, String password);
  Stream<User?> authStateChanges();
}

class Login {
  final AuthRepository repository;
  const Login(this.repository);
  Future<User> call(String email, String password) => repository.login(email, password);
}

Riverpod State Management

ScenarioProvider
Most appsRiverpod (async-first, testable, DI built-in)
Large team, strict unidirectionalBloc (explicit events/states)
Legacy or tinyProvider (simple, context-coupled)
final authStateProvider = StreamProvider<User?>((ref) {
  return ref.watch(authRepositoryProvider).authStateChanges();
});

final loginProvider = NotifierProvider<LoginNotifier, AsyncValue<void>>((ref) {
  return LoginNotifier(ref.watch(loginUseCaseProvider));
});

class LoginScreen extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final status = ref.watch(loginProvider);
    return status.when(
      loading: () => const CircularProgressIndicator(),
      error: (e, _) => ErrorWidget(message: e.toString()),
      data: (_) => const LoginForm(),
    );
  }
}

GoRouter with Auth Guard

final router = GoRouter(
  redirect: (context, state) {
    final isAuth = ref.read(authStateProvider).value != null;
    final isLogin = state.matchedLocation.startsWith('/login');
    if (!isAuth && !isLogin) return '/login';
    if (isAuth && isLogin) return '/';
    return null;
  },
  routes: [
    GoRoute(path: '/', builder: (_, __) => const HomeScreen()),
    GoRoute(path: '/login', builder: (_, __) => const LoginScreen()),
  ],
);

Impeller

Since Flutter 3.24+, Impeller is default on iOS. On Android, opt in:

// android/app/build.gradle
renderingEngine = "impeller"

Eliminates first-frame jank. Faster frame rendering. Better memory on low-end devices.

Platform Channels via Pigeon

// battery.dart (Pigeon input)
@HostApi()
abstract class BatteryApi {
  int getBatteryLevel();
}

Run: dart run pigeon --input battery.dart --dart_out lib/battery.dart

Performance Rules

  • const constructors everywhere
  • Consumer at leaf level (not entire screen)
  • ListView.builder / GridView.builder (lazy)
  • cached_network_image
  • Profile: flutter run --profile, DevTools
  • Avoid RepaintBoundary overuse

Perceived Performance

Flutter renders at 60fps on most devices and 120fps on ProMotion displays. Performance perception differs:

TechniquePerception impactImplementation
Skeleton loadersFeels faster than spinners. Shows structure immediately.shimmer package with matching layout shape
const constructorsWidgets that never change skip rebuild entirely. Cumulative gain on deep trees.const Text('...'), const SizedBox(...), const Icon(...)
extent estimation on scrollablesEliminates jank from recalculating item sizes during scroll.ListView.builder(itemExtent: 56.0, ...)
AnimatedSwitcher vs VisibilityFade transitions feel smoother than instant appear/disappear.Wrap changing content in AnimatedSwitcher(duration: 200ms)
RepaintBoundaryIsolates repaint of frequently-changing widgets (timers, animations) from rest of tree.Wrap animated clock/progress bar in RepaintBoundary

Error Handling

ScenarioCauseFix
Bad state: No elementEmpty stream/iterable accessed without checkGuard with .isEmpty or use .firstOrNull
LateInitializationErrorlate variable accessed before initUse nullable T? or StateNotifier with initial value
Platform channel: MissingPluginExceptionMethod not implemented on native sideVerify Pigeon codegen ran, check method name matches both sides
ConcurrentModificationErrorModifying list while iteratingUse .toList() to copy before mutation, or use List.unmodifiable
type 'Null' is not a subtype of type 'String'JSON null from API not handled in DTOAdd @JsonKey(defaultValue: '') or make fields nullable, run codegen
GoRouter: GoError: no routes for locationDeep link path not registeredAdd fallback redirect to / or register catch-all /* route
Riverpod: provider not disposedCircular dependency between providersUse ref.watch in build methods only, never in constructors. Break cycles with Provider.autoDispose
Build failed: Could not resolve all files (Android)Gradle dependency conflict or outdated pluginRun ./gradlew --refresh-dependencies, check build.gradle versions match AGP requirements

Production Checklist

  • Riverpod providers: domain → data → presentation layers
  • Domain layer: zero Flutter imports
  • GoRouter: auth redirect + deep linking
  • Impeller enabled on Android
  • const constructors everywhere
  • Platform channels via Pigeon (not manual MethodChannel)
  • Unit tests for domain layer
  • Widget tests for critical screens
  • CI/CD: Codemagic / GitHub Actions
  • ErrorWidget.builder + PlatformDispatcher.onError
  • Retry logic on network failures
  • Freezed / sealed classes for state unions

Anti-Patterns

Anti-patternFix
Business logic in widgetsExtract to Riverpod notifiers / use cases
ref.watch inside callbacksref.read for one-time reads
Giant widgets > 200 linesExtract into smaller widgets
Manual MethodChannelPigeon for type-safe channels
No error handling in AsyncValueHandle loading/error/data explicitly
One giant GoRouter fileSplit routes into feature modules

Review Format (Required)

When reviewing Flutter code, use Before | After | Why format:

BeforeAfterWhy
setState(() { count++; }) in large widgetref.watch(counterProvider.notifier).increment()setState triggers full widget rebuild; Riverpod isolates state changes
ListView(children: items.map((e) => Widget(e)).toList())ListView.builder(itemCount: items.length, itemBuilder: (_, i) => Widget(items[i]))Builder lazily constructs only visible items; map builds all upfront
Navigator.push(context, MaterialPageRoute(builder: (_) => Screen()))context.go('/route/${id}')GoRouter enables deep linking, typed params, and auth guards

Perceived Performance (Extended)

Flutter renders at 60fps on most devices, 120fps on ProMotion displays.

TechniquePerceptionImplementation
const constructorsWidgets that never change skip rebuild entirelyconst Text(...), const SizedBox(...)
RepaintBoundaryIsolates frequently-changing widgets (timers, animations)Wrap clock/progress bar in RepaintBoundary
Skeleton loadersShows structure immediately (feels faster than spinners)shimmer package with matching layout
itemExtent on listsEliminates jank from recalculating sizes during scrollListView.builder(itemExtent: 56.0)
AnimatedSwitcherFade transitions feel smoother than instant appear/disappearWrap changing content, set duration: 200ms
Hero animationsCreate continuity between screensHero(tag: 'avatar', child: ...) on source and destination
Pre-cache imagesEliminates flash-of-placeholder on revisitprecacheImage(NetworkImage(url), context) in initState

Rule: The user feels the slowest frame. Optimize for worst case, not average.

Sources

  • Flutter Documentation (flutter.dev)
  • Dart 3.7 Language Tour (dart.dev)
  • Riverpod Documentation (riverpod.dev)
  • GoRouter Documentation
  • Impeller Rendering Engine
  • Pigeon Plugin

Pre-Flight Checklist

Before submitting Flutter code:

  • All widgets use const constructors where possible (check with dart analyze)
  • Long lists use ListView.builder or SliverList.builder, never ListView(children: [...])
  • ref.watch only in build methods; ref.read only in callbacks
  • Routes use GoRouter typed parameters, not manual string parsing
  • AsyncValue has .when(data:, loading:, error:) — all three branches covered
  • Platform channels use Pigeon-generated code, never manual MethodChannel
  • android/app/build.gradle has renderingEngine = "impeller" (Android 14+)
  • No console.log or print() statements in production code
  • flutter analyze passes with zero errors or warnings
  • Tested on real Android device (not just iOS simulator or vice versa)
  • App works correctly when process is killed and restarted (state restoration)
  • Safe areas respected: MediaQuery.of(context).padding or SafeArea widget

Checklist

  • Skill loads without errors in the AI agent
  • YAML frontmatter is valid (description, compatibility, audience)
  • Workflow section provides clear step-by-step instructions
  • Error handling section covers common failure modes
  • All referenced files (references/, scripts/, assets/) exist
  • Skill triggers correctly for intended use cases
  • No broken links or missing resources
writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deploymentStars: 322kUpdated Claude CodeCodexVerifiedInstall
xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.Stars: 197kUpdated Claude CodeCodexVerifiedInstall
shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy.Stars: 119kUpdated Claude CodeCodexVerifiedInstall
childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release.Stars: 118kUpdated Claude CodeCodexVerifiedInstall