Communitygithub.com

dart-flutter-patterns

Padrões prontos para produção em Dart e Flutter, cobrindo null safety, estado imutável, composição assíncrona, arquitetura de widgets, gerenciamento de estado (BLoC, Riverpod, Provider), navegação GoRouter, rede Dio, geração de código Freezed e arquitetura limpa.

O que é dart-flutter-patterns?

Este skill oferece um conjunto abrangente de padrões de código Dart e Flutter prontos para uso em produção, todos centralizados em um único arquivo de documentação. Ele abrange desde fundamentos de null safety e estado imutável com classes sealed e Freezed, até composição assíncrona segura com `Future.wait` e proteção do `BuildContext` após `await`. Além disso, fornece orientação detalhada sobre arquitetura de widgets (extração em classes, propagação `const`, reconstruções escopadas), gerenciamento de estado com BLoC/Cubit e Riverpod (incluindo providers derivados e notifiers), navegação com GoRouter (incluindo guards de autenticação reativos), comunicação HTTP com Dio (com interceptadores e renovação de token) e tratamento de erros global. O skill também inclui exemplos de testes unitários e de widget. É uma referência prática e idiomática para desenvolvedores que estão iniciando novos projetos Flutter, revisando código existente ou implementando funcionalidades complexas, ajudando a evitar armadilhas comuns e a adotar as melhores práticas do ecossistema Dart/Flutter.

Funciona com~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/dart-flutter-patterns

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Padrões Dart/Flutter

Quando Usar

Use este skill quando:

  • Iniciar uma nova funcionalidade Flutter e precisar de padrões idiomáticos para gerenciamento de estado, navegação ou acesso a dados
  • Revisar ou escrever código Dart e precisar de orientação sobre null safety, tipos sealed ou composição assíncrona
  • Configurar um novo projeto Flutter e escolher entre BLoC, Riverpod ou Provider
  • Implementar clientes HTTP seguros, integração WebView ou armazenamento local
  • Escrever testes para widgets Flutter, Cubits ou providers Riverpod
  • Configurar GoRouter com guards de autenticação

Como Funciona

Este skill fornece padrões de código Dart/Flutter prontos para copiar e colar, organizados por assunto:

  1. Null safety — evite !, prefira ?./??/pattern matching
  2. Estado imutável — classes sealed, freezed, copyWith
  3. Composição assíncrona — Future.wait concorrente, BuildContext seguro após await
  4. Arquitetura de widgets — extraia para classes (não métodos), propagação const, reconstruções escopadas
  5. Gerenciamento de estado — eventos BLoC/Cubit, notifiers e providers derivados do Riverpod
  6. Navegação — GoRouter com guards de autenticação reativos via refreshListenable
  7. Rede — Dio com interceptadores, renovação de token com guard de retry único
  8. Tratamento de erros — captura global, ErrorWidget.builder, integração com crashlytics
  9. Testes — teste unitário (BLoC test), teste de widget (substituições ProviderScope), fakes em vez de mocks

Exemplos

// Estado sealed — previne estados impossíveis
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 com redirecionamento reativo de autenticação
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: [...],
);

// Provider derivado Riverpod com firstWhereOrNull seguro
@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;
  });
}

Padrões práticos e prontos para produção em aplicações Dart e Flutter. Agnósticos em relação a bibliotecas quando possível, com cobertura explícita dos pacotes mais comuns do ecossistema.


1. Fundamentos de Null Safety

Prefira Padrões ao Operador Bang

// RUIM — causa erro em tempo de execução se for nulo
final name = user!.name;

// BOM — fornece fallback
final name = user?.name ?? 'Desconhecido';

// BOM — pattern matching do Dart 3 (preferido para casos complexos)
final display = switch (user) {
  User(:final name, :final email) => '$name <$email>',
  null => 'Convidado',
};

// BOM — guarda com retorno antecipado
String getUserName(User? user) {
  if (user == null) return 'Desconhecido';
  return user.name; // promovido a não nulo após verificação
}

Evite Uso Excessivo de late

// RUIM — adia o erro de null para o tempo de execução
late String userId;

// BOM — anulável com inicialização explícita
String? userId;

// OK — use late apenas quando a inicialização é garantida antes do primeiro acesso
// (ex.: em initState() antes de qualquer interação com o widget)
late final AnimationController _controller;

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

2. Estado Imutável

Classes Sealed para Hierarquias de Estado

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 exaustivo — o compilador obriga a cobrir todos os casos
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 para Imutabilidade sem Boilerplate

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

// Uso
final user = User(id: '1', name: 'Alice', email: '[email protected]');
final updated = user.copyWith(name: 'Alice Smith'); // atualização imutável
final json = user.toJson();
final fromJson = User.fromJson(json);

3. Composição Assíncrona

Concorrência Estruturada com Future.wait

Future<DashboardData> loadDashboard(UserRepository users, OrderRepository orders) async {
  // Executa concorrentemente — não aguarde sequencialmente
  final (userList, orderList) = await (
    users.getAll(),
    orders.getRecent(),
  ).wait; // Desestruturação de registro Dart 3 + extensão Future.wait

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

Padrões com Stream

// Repositório expõe streams reativas para dados ao vivo
Stream<List<Item>> watchCartItems() => _db
    .watchTable('cart_items')
    .map((rows) => rows.map(Item.fromRow).toList());

// Na camada widget — declarativo, sem inscrição manual
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(),
  },
)

BuildContext Após Await

// CRÍTICO — sempre verifique mounted após qualquer await em StatefulWidget
Future<void> _handleSubmit() async {
  setState(() => _isLoading = true);
  try {
    await authService.login(_email, _password);
    if (!mounted) return; // ← proteção antes de usar 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. Arquitetura de Widgets

Extraia para Classes, Não Métodos

// RUIM — método privado que retorna widget, impede otimização
Widget _buildHeader() {
  return Container(
    padding: const EdgeInsets.all(16),
    child: Text(title, style: Theme.of(context).textTheme.headlineMedium),
  );
}

// BOM — classe de widget separada, permite const, reutilização de elemento
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),
    );
  }
}

Propagação const

// RUIM — novas instâncias a cada reconstrução
child: Padding(
  padding: EdgeInsets.all(16.0),       // não é const
  child: Icon(Icons.home, size: 24.0), // não é const
)

// BOM — const interrompe a propagação de reconstrução
child: const Padding(
  padding: EdgeInsets.all(16.0),
  child: Icon(Icons.home, size: 24.0),
)

Reconstruções Escopadas

// RUIM — página inteira é reconstruída a cada mudança no contador
class CounterPage extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final count = ref.watch(counterProvider); // reconstrói tudo
    return Scaffold(
      body: Column(children: [
        const ExpensiveHeader(), // reconstruído desnecessariamente
        Text('$count'),
        const ExpensiveFooter(), // reconstruído desnecessariamente
      ]),
    );
  }
}

// BOM — isole a parte que reconstroi
class CounterPage extends StatelessWidget {
  const CounterPage({super.key});

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Column(children: [
        ExpensiveHeader(),        // nunca reconstruído (const)
        _CounterDisplay(),        // apenas este reconstrói
        ExpensiveFooter(),        // nunca reconstruído (const)
      ]),
    );
  }
}

class _CounterDisplay extends ConsumerWidget {
  const _CounterDisplay();

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

5. Gerenciamento de Estado: BLoC/Cubit

// Cubit — estado síncrono ou assíncrono simples
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());
  }
}

// No widget
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. Gerenciamento de Estado: Riverpod

// Provider assíncrono com auto-dispose
@riverpod
Future<List<Product>> products(Ref ref) async {
  final repo = ref.watch(productRepositoryProvider);
  return repo.getAll();
}

// Notifier com mutações complexas
@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 = [];
}

// Provider derivado (padrão seletor)
@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 (do pacote collection) evita StateError quando o produto está faltando
    final product = products.firstWhereOrNull((p) => p.id == item.productId);
    return total + (product?.price ?? 0) * item.quantity;
  });
}

7. Navegação com GoRouter

final router = GoRouter(
  initialLocation: '/',
  // refreshListenable reavalia o redirecionamento sempre que o estado de autenticação muda
  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. HTTP com Dio

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'},
));

// Adiciona interceptador de autenticação
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 {
    // Proteção contra loops infinitos de retry: tenta renovar apenas uma vez por requisição
    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);
  },
));

// Repositório usando 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. Arquitetura de Tratamento de Erros

// Captura global de erros — configurada em 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 personalizado para produção
class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: router,
      builder: (context, child) {
        ErrorWidget.builder = (details) => MaterialErrorWidget(
          message: 'Algo deu errado. Por favor, tente novamente.',
          details: details.exception.toString(),
        );
        return child!;
      },
    );
  }
}

10. Testes

Teste de Unidade com BLoC

// Teste de Cubit unitário — sem Flutter
void main() {
  late AuthCubit sut;

  setUp(() {
    sut = AuthCubit(FakeAuthService());
  });

  test('emite loading e depois authenticated no login bem-sucedido', () async {
    expectLater(
      sut.stream,
      emitsInOrder([
        isA<AuthLoading>(),
        isA<AuthAuthenticated>(),
      ]),
    );

    await sut.login('[email protected]', 'senha');
  });

  test('emite loading e depois error na falha de login', () async {
    expectLater(
      sut.stream,
      emitsInOrder([
        isA<AuthLoading>(),
        isA<AuthError>(),
      ]),
    );

    await sut.login('[email protected]', 'senha');
  });
}

Teste de Widget com Riverpod

// Teste de widget — substitui providers reais
void main() {
  testWidgets('exibe produtos carregados', (tester) async {
    final overrides = [
      productsProvider.overrideWith((ref) => Future.value([
        Product(id: '1', name: 'Produto de Teste', price: 10.0),
      ])),
    ];

    await tester.pumpWidget(
      ProviderScope(
        overrides: overrides,
        child: const MaterialApp(home: ProductList()),
      ),
    );

    expect(find.text('Produto de Teste'), findsOneWidget);
  });
}

Prefira Fakes a Mocks

// FAKE — implementação leve e determinística
class FakeAuthService implements AuthService {
  @override
  Future<User> login(String email, String password) async {
    if (email == '[email protected]') throw AuthException('Credenciais inválidas');
    return User(id: '1', name: 'Teste', email: email);
  }

  @override
  void logout() {}
}

// Use mocks apenas para comportamento complexo que precisa ser verificado
// (quantas vezes um método foi chamado, com quais argumentos)
//@GenerateMocks([AnalyticsService])
void main() {
  test('registra evento de login no analytics', () {
    final analytics = MockAnalyticsService();
    when(analytics.logEvent('login_success', any)).thenAnswer((_) async {});

    // testa interação
    verify(analytics.logEvent('login_success', any)).called(1);
  });
}

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.

Habilidades Relacionadas