Communitygithub.com

Modèles Dart/Flutter

Modèles Dart et Flutter prêts pour la production, couvrant la null safety, l'état immuable, la composition asynchrone, l'architecture des widgets, les frameworks de gestion d'état populaires (BLoC, Riverpod, Provider), la navigation GoRouter, le réseau avec Dio, la génération de code Freezed et l'architecture propre. À utiliser lors de l'écriture ou de la révision de code Dart et Flutter — état, widgets, navigation, réseau ou architecture.

Qu'est-ce que Flutter ?

Ce modèle fournit des extraits de code Dart et Flutton prêts à l'emploi, organisés par préoccupation, pour guider les développeurs dans la mise en œuvre de solutions robustes et maintenables. Il couvre les fondamentaux de la null safety (en privilégiant les motifs plutôt que l'opérateur bang), l'état immuable avec les classes sealed et Freezed, la composition asynchrone avec Future.wait et la gestion du BuildContext après await, et l'architecture des widgets en extrayant les classes et en propageant const. Le modèle offre également des exemples concrets pour la gestion d'état avec BLoC/Cubit et Riverpod, la navigation réactive avec GoRouter et les gardes d'authentification, la mise en réseau avec Dio et les intercepteurs, la gestion globale des erreurs et les tests unitaires et de widgets. Il est conçu pour être agnostique vis-à-vis des bibliothèques lorsque cela est possible, tout en couvrant explicitement les packages les plus courants de l'écosystème Flutter.

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

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Que fait Flutter ?

Quand l'utiliser

Utilisez ce modèle lorsque :

  • Vous démarrez une nouvelle fonctionnalité Flutter et avez besoin de motifs idiomatiques pour la gestion d'état, la navigation ou l'accès aux données.
  • Vous révisez ou écrivez du code Dart et avez besoin de conseils sur la null safety, les types sealed ou la composition asynchrone.
  • Vous configurez un nouveau projet Flutter et choisissez entre BLoC, Riverpod ou Provider.
  • Vous implémentez des clients HTTP sécurisés, une intégration WebView ou un stockage local.
  • Vous écrivez des tests pour les widgets Flutter, les Cubits ou les providers Riverpod.
  • Vous mettez en place GoRouter avec des gardes d'authentification.

Comment ça fonctionne

Ce modèle fournit des modèles de code Dart/Flutter prêts à copier-coller, organisés par préoccupation :

  1. Null safety — éviter !, préférer ?./??/le filtrage par motif
  2. État immuable — classes sealed, freezed, copyWith
  3. Composition asynchrone — Future.wait concurrent, BuildContext sûr après await
  4. Architecture des widgets — extraire dans des classes (pas des méthodes), propagation const, reconstructions limitées
  5. Gestion d'état — événements BLoC/Cubit, notificateurs Riverpod et providers dérivés
  6. Navigation — GoRouter avec gardes d'authentification réactives via refreshListenable
  7. Réseau — Dio avec intercepteurs, rafraîchissement de token avec protection de tentative unique
  8. Gestion des erreurs — capture globale, ErrorWidget.builder, connexion Crashlytics
  9. Tests — tests unitaires (test BLoC), tests de widgets (remplacements ProviderScope), fakes plutôt que mocks

Exemples

// État sealed — empêche les états impossibles
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 avec redirection d'authentification réactive
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 dérivé Riverpod avec firstWhereOrNull sécurisé
@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;
  });
}

Des modèles pratiques et prêts pour la production pour les applications Dart et Flutter. Aussi agnostiques que possible vis-à-vis des bibliothèques, avec une couverture explicite des packages les plus courants de l'écosystème.


1. Fondamentaux de la Null Safety

Préférer les motifs à l'opérateur Bang

// MAUVAIS — plante à l'exécution si null
final name = user!.name;

// BON — fournir une valeur de repli
final name = user?.name ?? 'Inconnu';

// BON — filtrage par motif Dart 3 (préféré pour les cas complexes)
final display = switch (user) {
  User(:final name, :final email) => '$name <$email>',
  null => 'Invité',
};

// BON — retour anticipé avec garde
String getUserName(User? user) {
  if (user == null) return 'Inconnu';
  return user.name; // promu à non-null après la vérification
}

Éviter l'utilisation excessive de late

// MAUVAIS — reporte l'erreur null à l'exécution
late String userId;

// BON — nullable avec initialisation explicite
String? userId;

// OK — utiliser late uniquement lorsque l'initialisation est garantie avant le premier accès
// (par exemple, dans initState() avant toute interaction avec le widget)
late final AnimationController _controller;

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

2. État Immuable

Classes Scellées pour les Hiérarchies d'États

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 exhaustif — le compilateur impose toutes les 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 pour une Immuabilité sans Code 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);
}

// Utilisation
final user = User(id: '1', name: 'Alice', email: '[email protected]');
final updated = user.copyWith(name: 'Alice Smith'); // mise à jour immuable
final json = user.toJson();
final fromJson = User.fromJson(json);

3. Composition Asynchrone

Concurrence Structurée avec Future.wait

Future<DashboardData> loadDashboard(UserRepository users, OrderRepository orders) async {
  // Exécuter en concurrence — ne pas attendre séquentiellement
  final (userList, orderList) = await (
    users.getAll(),
    orders.getRecent(),
  ).wait; // Destructuration d'enregistrement Dart 3 + extension Future.wait

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

Motifs de Stream

// Le repository expose des streams réactifs pour les données en direct
Stream<List<Item>> watchCartItems() => _db
    .watchTable('cart_items')
    .map((rows) => rows.map(Item.fromRow).toList());

// Dans la couche widget — déclaratif, pas d'abonnement manuel
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 Après Await

// CRITIQUE — toujours vérifier mounted après tout await dans StatefulWidget
Future<void> _handleSubmit() async {
  setState(() => _isLoading = true);
  try {
    await authService.login(_email, _password);
    if (!mounted) return; // ← garde avant d'utiliser le contexte
    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. Architecture des Widgets

Extraire dans des Classes, Pas des Méthodes

// MAUVAIS — méthode privée retournant un widget, empêche l'optimisation
Widget _buildHeader() {
  return Container(
    padding: const EdgeInsets.all(16),
    child: Text(title, style: Theme.of(context).textTheme.headlineMedium),
  );
}

// BON — classe widget séparée, permet const, réutilisation d'élément
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),
    );
  }
}

Propagation de const

// MAUVAIS — nouvelles instances à chaque reconstruction
child: Padding(
  padding: EdgeInsets.all(16.0),       // pas const
  child: Icon(Icons.home, size: 24.0), // pas const
)

// BON — const arrête la propagation de la reconstruction
child: const Padding(
  padding: EdgeInsets.all(16.0),
  child: Icon(Icons.home, size: 24.0),
)

Reconstructions Limitées

// MAUVAIS — la page entière se reconstruit à chaque changement de compteur
class CounterPage extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final count = ref.watch(counterProvider); // reconstruit tout
    return Scaffold(
      body: Column(children: [
        const ExpensiveHeader(), // reconstruit inutilement
        Text('$count'),
        const ExpensiveFooter(), // reconstruit inutilement
      ]),
    );
  }
}

// BON — isoler la partie qui se reconstruit
class CounterPage extends StatelessWidget {
  const CounterPage({super.key});

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Column(children: [
        ExpensiveHeader(),        // jamais reconstruit (const)
        _CounterDisplay(),        // seulement celui-ci se reconstruit
        ExpensiveFooter(),        // jamais reconstruit (const)
      ]),
    );
  }
}

class _CounterDisplay extends ConsumerWidget {
  const _CounterDisplay();

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

5. Gestion d'État : BLoC/Cubit

// Cubit — état synchrone ou asynchrone simple
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());
  }
}

// Dans le 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. Gestion d'État : Riverpod

// Provider asynchrone à auto-suppression
@riverpod
Future<List<Product>> products(Ref ref) async {
  final repo = ref.watch(productRepositoryProvider);
  return repo.getAll();
}

// Notificateur avec mutations complexes
@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 dérivé (motif sélecteur)
@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 (du package collection) évite StateError lorsque le produit est manquant
    final product = products.firstWhereOrNull((p) => p.id == item.productId);
    return total + (product?.price ?? 0) * item.quantity;
  });
}

7. Navigation avec GoRouter

final router = GoRouter(
  initialLocation: '/',
  // refreshListenable réévalue la redirection à chaque changement d'état d'authentification
  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 avec 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'},
));

// Ajouter un intercepteur d'authentification
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 {
    // Protection contre les boucles de nouvelle tentative infinies : ne tenter le rafraîchissement qu'une fois par requête
    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);
  },
));

// Repository utilisant 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. Architecture de Gestion des Erreurs

// Capture globale des erreurs — à configurer dans 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 personnalisé pour la production
class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) {
    // ...

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.

Skills associés