Communitygithub.com

dart-flutter-patterns

프로덕션 수준의 Dart 및 Flutter 패턴을 제공합니다. 널 안전성, 불변 상태, 비동기 구성, 위젯 아키텍처, 주요 상태 관리 프레임워크(BLoC, Riverpod, Provider), GoRouter 네비게이션, Dio 네트워킹, Freezed 코드 생성, 클린 아키텍처를 다룹니다. Dart 및 Flutter 코드(상태, 위젯, 네비게이션, 네트워킹, 아키텍처)를 작성하거나 리뷰할 때 사용하세요.

dart-flutter-patterns란 무엇인가요?

이 스킬은 Dart와 Flutter 애플리케이션 개발 시 프로덕션 수준의 모범 사례와 패턴을 제공합니다. 널 안전성, 불변 상태, 비동기 처리, 위젯 설계, 상태 관리, 네비게이션, 네트워킹, 오류 처리, 테스트 등 핵심 영역을 다룹니다. 각 패턴은 복사하여 바로 사용할 수 있는 코드 예제와 함께 제공되어, 개발자가 일관되고 안정적인 코드를 신속하게 작성할 수 있도록 돕습니다. 주요 상태 관리 라이브러리(BLoC, Riverpod, Provider)와 GoRouter, Dio, Freezed와 같은 인기 있는 패키지를 명시적으로 지원하며, 특정 라이브러리에 종속되지 않는 일반적인 패턴도 함께 제공하여 다양한 프로젝트 환경에 적용할 수 있습니다. 이 스킬은 특히 새로운 Flutter 프로젝트를 시작하거나 기존 코드를 리팩토링할 때 유용하며, 가독성이 높고 유지보수하기 쉬운 코드를 작성하는 데 중점을 둡니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/dart-flutter-patterns

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Dart/Flutter 패턴

사용 시기

다음과 같은 경우에 이 스킬을 사용하세요:

  • 새로운 Flutter 기능을 시작하고 상태 관리, 네비게이션 또는 데이터 액세스를 위한 관용적인 패턴이 필요할 때
  • Dart 코드를 리뷰하거나 작성하면서 널 안전성, sealed 타입 또는 비동기 구성에 대한 지침이 필요할 때
  • 새로운 Flutter 프로젝트를 설정하고 BLoC, Riverpod 또는 Provider 중에서 선택할 때
  • 안전한 HTTP 클라이언트, WebView 통합 또는 로컬 스토리지를 구현할 때
  • Flutter 위젯, Cubit 또는 Riverpod 프로바이더에 대한 테스트를 작성할 때
  • 인증 가드가 있는 GoRouter를 연결할 때

작동 방식

이 스킬은 관심사별로 구성된 복사-붙여넣기 가능한 Dart/Flutter 코드 패턴을 제공합니다:

  1. 널 안전성 — ! 사용을 피하고 ?./??/패턴 매칭 선호
  2. 불변 상태 — sealed 클래스, freezed, copyWith
  3. 비동기 구성 — 동시 Future.wait, await 후 안전한 BuildContext
  4. 위젯 아키텍처 — 메서드가 아닌 클래스로 추출, const 전파, 범위 재구축
  5. 상태 관리 — BLoC/Cubit 이벤트, Riverpod 노티파이어 및 파생 프로바이더
  6. 네비게이션 — refreshListenable을 통한 반응형 인증 가드가 있는 GoRouter
  7. 네트워킹 — 인터셉터, 일회성 재시도 가드가 있는 토큰 갱신을 사용하는 Dio
  8. 오류 처리 — 전역 캡처, ErrorWidget.builder, Crashlytics 연결
  9. 테스팅 — 단위(BLoC 테스트), 위젯(ProviderScope 재정의), Mock 대신 Fake 사용

예시

// Sealed 상태 — 불가능한 상태 방지
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
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: [...],
);

// 안전한 firstWhereOrNull을 사용한 Riverpod 파생 프로바이더
@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;
  });
}

Dart 및 Flutter 애플리케이션을 위한 실용적이고 프로덕션 수준의 패턴입니다. 가능하면 라이브러리 중립적이며, 가장 일반적인 에코시스템 패키지를 명시적으로 다룹니다.


1. 널 안전성 기본

뱅 연산자보다 패턴 선호

// BAD — null인 경우 런타임에 크래시 발생
final name = user!.name;

// GOOD — 대체값 제공
final name = user?.name ?? 'Unknown';

// GOOD — Dart 3 패턴 매칭 (복잡한 경우 선호)
final display = switch (user) {
  User(:final name, :final email) => '$name <$email>',
  null => 'Guest',
};

// GOOD — 조기 반환 보호
String getUserName(User? user) {
  if (user == null) return 'Unknown';
  return user.name; // 검사 후 null이 아닌 것으로 승격
}

late 남용 피하기

// BAD — 널 오류를 런타임으로 지연시킴
late String userId;

// GOOD — 명시적 초기화로 nullable
String? userId;

// OK — 첫 액세스 전 초기화가 보장되는 경우에만 late 사용
// (예: 위젯 상호 작용 전 initState())
late final AnimationController _controller;

@override
void initState() {
  super.initState();
  _controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 300));
}

2. 불변 상태

상태 계층 구조를 위한 Sealed 클래스

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;
}

// 철저한 switch — 컴파일러가 모든 분기를 강제함
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

import 'package:freezed_annotation/freezed_annotation.dart';

part 'user.freezed.dart';
part 'user.g.dart';

@freezed
class User with _$User {
  const factory User({
    required String id,
    required String name,
    required String email,
    @Default(false) bool isAdmin,
  }) = _User;

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
}

// 사용법
final user = User(id: '1', name: 'Alice', email: '[email protected]');
final updated = user.copyWith(name: 'Alice Smith'); // 불변 업데이트
final json = user.toJson();
final fromJson = User.fromJson(json);

3. 비동기 구성

Future.wait를 사용한 구조적 동시성

Future<DashboardData> loadDashboard(UserRepository users, OrderRepository orders) async {
  // 동시에 실행 — 순차적으로 await하지 않음
  final (userList, orderList) = await (
    users.getAll(),
    orders.getRecent(),
  ).wait; // Dart 3 레코드 구조 분해 + Future.wait 확장

  return DashboardData(users: userList, orders: orderList);
}

스트림 패턴

// 저장소는 실시간 데이터를 위한 반응형 스트림을 노출
Stream<List<Item>> watchCartItems() => _db
    .watchTable('cart_items')
    .map((rows) => rows.map(Item.fromRow).toList());

// 위젯 계층 — 선언적, 수동 구독 없음
StreamBuilder<List<Item>>(
  stream: cartRepository.watchCartItems(),
  builder: (context, snapshot) => switch (snapshot) {
    AsyncSnapshot(connectionState: ConnectionState.waiting) =>
        const CircularProgressIndicator(),
    AsyncSnapshot(:final error?) => ErrorWidget(error.toString()),
    AsyncSnapshot(:final data?) => CartList(items: data),
    _ => const SizedBox.shrink(),
  },
)

Await 후 BuildContext

// 중요 — StatefulWidget에서 await 후 항상 mounted 확인
Future<void> _handleSubmit() async {
  setState(() => _isLoading = true);
  try {
    await authService.login(_email, _password);
    if (!mounted) return; // ← context 사용 전 보호
    context.go('/home');
  } on AuthException catch (e) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(e.message)));
  } finally {
    if (mounted) setState(() => _isLoading = false);
  }
}

4. 위젯 아키텍처

메서드가 아닌 클래스로 추출

// BAD — 위젯을 반환하는 private 메서드, 최적화 방해
Widget _buildHeader() {
  return Container(
    padding: const EdgeInsets.all(16),
    child: Text(title, style: Theme.of(context).textTheme.headlineMedium),
  );
}

// GOOD — 별도 위젯 클래스, const 및 요소 재사용 가능
class _PageHeader extends StatelessWidget {
  const _PageHeader(this.title);
  final String title;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Text(title, style: Theme.of(context).textTheme.headlineMedium),
    );
  }
}

const 전파

// BAD — 재빌드마다 새 인스턴스 생성
child: Padding(
  padding: EdgeInsets.all(16.0),       // const 아님
  child: Icon(Icons.home, size: 24.0), // const 아님
)

// GOOD — const가 재빌드 전파를 막음
child: const Padding(
  padding: EdgeInsets.all(16.0),
  child: Icon(Icons.home, size: 24.0),
)

범위 재구축

// BAD — 카운터가 변경될 때마다 전체 페이지 재빌드
class CounterPage extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final count = ref.watch(counterProvider); // 모든 것을 재빌드
    return Scaffold(
      body: Column(children: [
        const ExpensiveHeader(), // 불필요하게 재빌드됨
        Text('$count'),
        const ExpensiveFooter(), // 불필요하게 재빌드됨
      ]),
    );
  }
}

// GOOD — 재빌드 부분 분리
class CounterPage extends StatelessWidget {
  const CounterPage({super.key});

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Column(children: [
        ExpensiveHeader(),        // 절대 재빌드되지 않음 (const)
        _CounterDisplay(),        // 이것만 재빌드됨
        ExpensiveFooter(),        // 절대 재빌드되지 않음 (const)
      ]),
    );
  }
}

class _CounterDisplay extends ConsumerWidget {
  const _CounterDisplay();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final count = ref.watch(counterProvider);
    return Text('$count');
  }
}

5. 상태 관리: BLoC/Cubit

// Cubit — 동기 또는 간단한 비동기 상태
class AuthCubit extends Cubit<AuthState> {
  AuthCubit(this._authService) : super(const AuthState.initial());
  final AuthService _authService;

  Future<void> login(String email, String password) async {
    emit(const AuthState.loading());
    try {
      final user = await _authService.login(email, password);
      emit(AuthState.authenticated(user));
    } on AuthException catch (e) {
      emit(AuthState.error(e.message));
    }
  }

  void logout() {
    _authService.logout();
    emit(const AuthState.initial());
  }
}

// 위젯에서 사용
BlocBuilder<AuthCubit, AuthState>(
  builder: (context, state) => switch (state) {
    AuthInitial() => const LoginForm(),
    AuthLoading() => const CircularProgressIndicator(),
    AuthAuthenticated(:final user) => HomePage(user: user),
    AuthError(:final message) => ErrorView(message: message),
  },
)

6. 상태 관리: Riverpod

// 자동 폐기 async 프로바이더
@riverpod
Future<List<Product>> products(Ref ref) async {
  final repo = ref.watch(productRepositoryProvider);
  return repo.getAll();
}

// 복잡한 변형을 위한 Notifier
@riverpod
class CartNotifier extends _$CartNotifier {
  @override
  List<CartItem> build() => [];

  void add(Product product) {
    final existing = state.where((i) => i.productId == product.id).firstOrNull;
    if (existing != null) {
      state = [
        for (final item in state)
          if (item.productId == product.id) item.copyWith(quantity: item.quantity + 1)
          else item,
      ];
    } else {
      state = [...state, CartItem(productId: product.id, quantity: 1)];
    }
  }

  void remove(String productId) =>
      state = state.where((i) => i.productId != productId).toList();

  void clear() => state = [];
}

// 파생 프로바이더 (선택자 패턴)
@riverpod
int cartCount(Ref ref) => ref.watch(cartNotifierProvider).length;

@riverpod
double cartTotal(Ref ref) {
  final cart = ref.watch(cartNotifierProvider);
  final products = ref.watch(productsProvider).valueOrNull ?? [];
  return cart.fold(0.0, (total, item) {
    // firstWhereOrNull (collection 패키지에서 제공)은 제품이 없을 때 StateError를 방지합니다
    final product = products.firstWhereOrNull((p) => p.id == item.productId);
    return total + (product?.price ?? 0) * item.quantity;
  });
}

7. GoRouter를 사용한 네비게이션

final router = GoRouter(
  initialLocation: '/',
  // refreshListenable은 인증 상태가 변경될 때마다 리디렉션을 재평가합니다
  refreshListenable: GoRouterRefreshStream(authCubit.stream),
  redirect: (context, state) {
    final isLoggedIn = context.read<AuthCubit>().state is AuthAuthenticated;
    final isGoingToLogin = state.matchedLocation == '/login';
    if (!isLoggedIn && !isGoingToLogin) return '/login';
    if (isLoggedIn && isGoingToLogin) return '/';
    return null;
  },
  routes: [
    GoRoute(path: '/login', builder: (_, __) => const LoginPage()),
    ShellRoute(
      builder: (context, state, child) => AppShell(child: child),
      routes: [
        GoRoute(path: '/', builder: (_, __) => const HomePage()),
        GoRoute(
          path: '/products/:id',
          builder: (context, state) =>
              ProductDetailPage(id: state.pathParameters['id']!),
        ),
      ],
    ),
  ],
);

8. Dio를 사용한 HTTP

final dio = Dio(BaseOptions(
  baseUrl: const String.fromEnvironment('API_URL'),
  connectTimeout: const Duration(seconds: 10),
  receiveTimeout: const Duration(seconds: 30),
  headers: {'Content-Type': 'application/json'},
));

// 인증 인터셉터 추가
dio.interceptors.add(InterceptorsWrapper(
  onRequest: (options, handler) async {
    final token = await secureStorage.read(key: 'auth_token');
    if (token != null) options.headers['Authorization'] = 'Bearer $token';
    handler.next(options);
  },
  onError: (error, handler) async {
    // 무한 재시도 루프 방지: 요청당 한 번만 갱신 시도
    final isRetry = error.requestOptions.extra['_isRetry'] == true;
    if (!isRetry && error.response?.statusCode == 401) {
      final refreshed = await attemptTokenRefresh();
      if (refreshed) {
        error.requestOptions.extra['_isRetry'] = true;
        return handler.resolve(await dio.fetch(error.requestOptions));
      }
    }
    handler.next(error);
  },
));

// Dio를 사용하는 저장소
class UserApiDataSource {
  const UserApiDataSource(this._dio);
  final Dio _dio;

  Future<User> getById(String id) async {
    final response = await _dio.get<Map<String, dynamic>>('/users/$id');
    return User.fromJson(response.data!);
  }
}

9. 오류 처리 아키텍처

// 전역 오류 캡처 — main()에서 설정
void main() {
  FlutterError.onError = (details) {
    FlutterError.presentError(details);
    crashlytics.recordFlutterFatalError(details);
  };

  PlatformDispatcher.instance.onError = (error, stack) {
    crashlytics.recordError(error, stack, fatal: true);
    return true;
  };

  runApp(const App());
}

// 프로덕션용 사용자 정의 ErrorWidget
class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      …

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

관련 스킬