Communitygithub.com

dart-flutter-patterns

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

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

이 스킬은 Dart와 Flutter 애플리케이션 개발 시 프로덕션 환경에서 즉시 사용 가능한 코드 패턴과 모범 사례를 제공합니다. 널 안전성(Null Safety)의 근본 원칙부터 불변 상태(Immutable State) 관리를 위한 sealed class와 Freezed 사용법, Future.wait를 활용한 비동기 동시성 처리, 위젯 재사용성 최적화를 위한 const 전파 및 위젯 추출 기법, BLoC/Cubit과 Riverpod을 이용한 상태 관리 패턴, GoRouter의 refreshListenable을 통한 인증 가드 구현, Dio 인터셉터 기반의 토큰 갱신 로직, 전역 오류 처리, 그리고 각 계층별 테스트 전략까지 포괄합니다. Dart 3의 패턴 매칭과 레코드(Record) 문법을 적극 활용하여 최신 언어 기능과의 일관성을 유지하며, 특정 라이브러리에 종속되지 않으면서도 가장 널리 사용되는 Flutter 생태계 패키지(BLoC, Riverpod, Provider, GoRouter, Dio, Freezed)를 명시적으로 지원합니다. 복잡한 기능 구현 시 참조할 수 있는 실용적인 템플릿으로, 초보자부터 숙련된 개발자까지 생산성 향상과 코드 품질 개선에 도움을 줍니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/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 class, freezed, copyWith
  3. 비동기 구성 — 동시 Future.wait, await 후 안전한 BuildContext
  4. 위젯 아키텍처 — 메서드 대신 클래스 추출, const 전파, 범위 제한 재빌드
  5. 상태 관리 — BLoC/Cubit 이벤트, Riverpod notifier 및 파생 프로바이더
  6. 네비게이션 — refreshListenable을 통한 반응형 인증 가드가 있는 GoRouter
  7. 네트워킹 — 인터셉터, 1회 재시도 가드가 있는 토큰 갱신을 포함한 Dio
  8. 오류 처리 — 전역 캡처, ErrorWidget.builder, Crashlytics 연결
  9. 테스트 — 단위 테스트(BLoC 테스트), 위젯 테스트(ProviderScope 오버라이드), 모의 객체보다 가짜 객체(fakes)

예제

// Sealed state — 불가능한 상태 방지
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. 널 안전성 기본

뱅 연산자보다 패턴 선호

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

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

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

// 좋음 — 조기 반환으로 보호
String getUserName(User? user) {
  if (user == null) return 'Unknown';
  return user.name; // 검사 후 non-null로 승격
}

late 과도 사용 금지

// 나쁨 — 널 오류를 런타임으로 지연
late String userId;

// 좋음 — 명시적 초기화로 nullable 선언
String? userId;

// 괜찮음 — 초기화가 첫 번째 접근 전에 보장되는 경우에만 late 사용
// (예: initState()에서 위젯 상호작용 전)
late final AnimationController _controller;

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

2. 불변 상태

상태 계층 구조를 위한 Sealed Class

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 — 컴파일러가 모든 분기 강제
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. 위젯 아키텍처

메서드 대신 클래스로 추출

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

// 좋음 — 별도 위젯 클래스, 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 전파

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

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

범위 제한 재빌드

// 나쁨 — 카운터가 변경될 때마다 전체 페이지 재빌드
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(), // 불필요하게 재빌드됨
      ]),
    );
  }
}

// 좋음 — 재빌드되는 부분만 분리
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(
      routerConfig: router,
      builder: (context, widget) {
        ErrorWidget.builder = (details) => const _ProductionErrorWidget();
        return widget!;
      },
    );
  }
}

class _ProductionErrorWidget extends StatelessWidget {
  const _ProductionErrorWidget();

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, size: 64, color: Colors.red),
            const SizedBox(height: 16),
            Text(
              '문제가 발생했습니다.',
              style: Theme.of(context).textTheme.headlineSmall,
            ),
            const SizedBox(height: 8),
            const Text('잠시 후 다시 시도해 주세요.'),
          ],
        ),
      ),
    );
  }
}

10. 테스트

BLoC/Cubit 단위 테스트

void main() {
  group('AuthCubit', () {
    late MockAuthService authService;
    late AuthCubit cubit;

    setUp(() {
      authService = MockAuthService();
      cubit = AuthCubit(authService);
    });

    tearDown(() => cubit.close());

    test('초기 상태는 AuthInitial', () {
      expect(cubit.state, const AuthState.initial());
    });

    blocTest<AuthCubit, AuthState>(
      '로그인 성공 시 AuthAuthenticated 방출',
      build: () => cubit,
      act: (cubit) => cubit.login('[email protected]', 'pass'),
      setUp: () => when(() => authService.login(any(), any()))
          .thenAnswer((_) async => User(id: '1', name: 'Alice', email: '[email protected]')),
      expect: () => [
        const AuthState.loading(),
        isA<AuthAuthenticated>(),
      ],
    );
  });
}

Riverpod 프로바이더 테스트

void main() {
  test('totalCost는 모든 아이템의 가격 합계를 반환', () async {
    final container = ProviderContainer(
      overrides: [
        productsProvider.overrideWith((ref) => Future.value([
          Product(id: '1', name: 'Item', price: 10.0),
          Product(id: '2', name: 'Item 2', price: 20.0),
        ])),
        cartNotifierProvider.overrideWith((ref) => [
          CartItem(productId: '1', quantity: 2),
          CartItem(productId: '2', quantity: 1),
        ]),
      ],
    );
    addTearDown(container.dispose);

    final total = container.read(cartTotalProvider);
    expect(total, 40.0); // 2 * 10 + 1 * 20
  });
}

위젯 테스트

void main() {
  testWidgets('CartPage는 빈 카트일 때 메시지 표시', (tester) async {
    await tester.pumpWidget(
      ProviderScope(
        overrides: [
          cartNotifierProvider.overrideWith((ref) => []),
        ],
        child: const MaterialApp(home: CartPage()),
      ),
    );

    expect(find.text('장바구니가 비어 있습니다'), findsOneWidget);
  });
}

참고 자료

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/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

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.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

관련 스킬