dart-flutter-patterns
하는 일
이 가이드는 Dart와 Flutter의 바로 쓸 수 있는 코드 예시를 제공합니다. null 안전성, 상태 관리, 내비게이션 등에서 모범 사례에 따라 코드를 구성하는 방법을 가르칩니다.
사용하는 경우
- ✓새 Flutter 프로젝트를 시작할 때.
- ✓데이터나 내비게이션을 관리하는 패턴이 필요할 때.
- ✓코드가 모범 사례를 따르는지 검토할 때.
스킬 링크
https://github.com/affaan-m/ECC/blob/main/pi/core/skills/dart-flutter-patterns/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“BLoC이나 Riverpod을 사용해 Flutter 앱의 상태를 효율적으로 관리하려면 어떻게 해야 하나요?”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
null 안전성, 불변 상태, 상태 관리, 내비게이션 같은 주제별로 정리된, 복사해서 붙여 넣을 수 있는 코드 조각을 제공합니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
Dart/Flutter Patterns
When to Use
Use this skill when:
- Starting a new Flutter feature and need idiomatic patterns for state management, navigation, or data access
- Reviewing or writing Dart code and need guidance on null safety, sealed types, or async composition
- Setting up a new Flutter project and choosing between BLoC, Riverpod, or Provider
- Implementing secure HTTP clients, WebView integration, or local storage
- Writing tests for Flutter widgets, Cubits, or Riverpod providers
- Wiring up GoRouter with authentication guards
How It Works
This skill provides copy-paste-ready Dart/Flutter code patterns organized by concern:
- Null safety — avoid
!, prefer?./??/pattern matching - Immutable state — sealed classes,
freezed,copyWith - Async composition — concurrent
Future.wait, safeBuildContextafterawait - Widget architecture — extract to classes (not methods),
constpropagation, scoped rebuilds - State management — BLoC/Cubit events, Riverpod notifiers and derived providers
- Navigation — GoRouter with reactive auth guards via
refreshListenable - Networking — Dio with interceptors, token refresh with one-time retry guard
- Error handling — global capture,
ErrorWidget.builder, crashlytics wiring - Testing — unit (BLoC test), widget (ProviderScope overrides), fakes over mocks
Examples
// Sealed state — prevents impossible states
sealed class AsyncState<T> {}
final class Loading<T> extends AsyncState<T> {}
final class Success<T> extends AsyncState<T> { final T data; const Success(this.data); }
final class Failure<T> extends AsyncState<T> { final Object error; const Failure(this.error); }
// GoRouter with reactive auth redirect
final router = GoRouter(
refreshListenable: GoRouterRefreshStream(authCubit.stream),
redirect: (context, state) {
final authed = context.read<AuthCubit>().state is AuthAuthenticated;
if (!authed && !state.matchedLocation.startsWith('/login')) return '/login';
return null;
},
routes: [...],
);
// Riverpod derived provider with safe firstWhereOrNull
@riverpod
double cartTotal(Ref ref) {
final cart = ref.watch(cartNotifierProvider);
final products = ref.watch(productsProvider).valueOrNull ?? [];
return cart.fold(0.0, (total, item) {
final product = products.firstWhereOrNull((p) => p.id == item.productId);
return total + (product?.price ?? 0) * item.quantity;
});
}
Practical, production-ready patterns for Dart and Flutter applications. Library-agnostic where possible, with explicit coverage of the most common ecosystem packages.
1. Null Safety Fundamentals
Prefer Patterns Over Bang Operator
// BAD — crashes at runtime if null
final name = user!.name;
// GOOD — provide fallback
final name = user?.name ?? 'Unknown';
// GOOD — Dart 3 pattern matching (preferred for complex cases)
final display = switch (user) {
User(:final name, :final email) => '$name <$email>',
null => 'Guest',
};
// GOOD — guard early return
String getUserName(User? user) {
if (user == null) return 'Unknown';
return user.name; // promoted to non-null after check
}
Avoid late Overuse
// BAD — defers null error to runtime
late String userId;
// GOOD — nullable with explicit initialization
String? userId;
// OK — use late only when initialization is guaranteed before first access
// (e.g., in initState() before any widget interaction)
late final AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 300));
}
2. Immutable State
Sealed Classes for State Hierarchies
sealed class UserState {}
final class UserInitial extends UserState {}
final class UserLoading extends UserState {}
final class UserLoaded extends UserState {
const UserLoaded(this.user);
final User user;
}
final class UserError extends UserState {
const UserError(this.message);
final String message;
}
// Exhaustive switch — compiler enforces all branches
Widget buildFrom(UserState state) => switch (state) {
UserInitial() => const SizedBox.shrink(),
UserLoading() => const CircularProgressIndicator(),
UserLoaded(:final user) => UserCard(user: user),
UserError(:final message) => ErrorText(message),
};
Freezed for Boilerplate-Free Immutability
…
자주 묻는 질문
'null 안전성'이란 무엇인가요?
값이 있어야 할 변수가 비어(null) 있을 때 생기는 흔한 오류를 막아 주는 Dart 기능입니다.
'불변 상태'란 무엇을 뜻하나요?
데이터가 한번 만들어지면 직접 바꿀 수 없다는 뜻입니다. 수정하려면 새 버전의 데이터를 만들어야 하므로 코드가 더 예측 가능해집니다.
어떤 상태 관리 도구를 다루나요?
가장 인기 있는 BLoC/Cubit, Riverpod, Provider를 다룹니다.
상세 정보
작성자의 원본 설명
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.
repo: affaan-m/ECC
인기도
- GitHub 스타
- 280k
- 순위
- #161
- 라이선스
- MIT
- 업데이트
- 2026. 10. 15.
댓글
- …
이 저장소의 다른 스킬
accessibility
280k에이전트가 모든 사람이 쓸 수 있는 인터페이스를 만들도록 돕습니다. 시각 장애나 운동 장애가 있는 사람도 쓸 수 있게 합니다.
agent-architecture-audit
280k에이전트가 모든 것이 올바르게 작동하는지 점검하도록 돕습니다. AI 시스템의 문제를 찾아 고쳐서 기대대로 작동하게 합니다.
agent-eval
280k에이전트가 서로 다른 AI 코딩 도구를 비교하도록 돕습니다. 특정 작업에서 어느 도구가 더 빠르고, 저렴하고, 믿을 만한지 측정합니다.
agent-harness-construction
280k에이전트가 작업을 더 잘 이해하도록 돕습니다. 에이전트가 쓰는 도구와 지시문을 최적화해 성공 가능성을 높입니다.
비슷한 스킬
flutter-animating-apps
101kFlutter 앱에 애니메이션 효과와 전환을 추가하도록 돕습니다. iOS와 Android 앱에서 움직임과 시각 디자인을 만드는 데 유용합니다.
agent-spec-mobile-react-native
81kReact Native로 iPhone과 Android용 모바일 앱을 만들도록 돕습니다. 화면, 내비게이션, 네이티브 모듈을 포함합니다.
orientation
75k에이전트가 세로와 가로 방향 모두에서 사이트가 작동하도록 도와, 방향 잠금과 기기를 돌리라는 메시지를 없애 누구나 콘텐츠에 접근하게 합니다.