dart-flutter-patterns
Skill này làm gì
Hướng dẫn này cung cấp các ví dụ code Dart và Flutter có thể dùng ngay. Nó chỉ bạn cách tổ chức code theo thực hành tốt nhất về null safety, quản lý trạng thái, điều hướng và nhiều nội dung khác.
Khi nào nên dùng
- ✓Khi bắt đầu một dự án Flutter mới.
- ✓Khi cần một mẫu để quản lý dữ liệu hoặc điều hướng.
- ✓Khi xem lại code để chắc chắn nó tuân theo thực hành tốt nhất.
Liên kết skill
https://github.com/affaan-m/ECC/blob/main/pi/core/skills/dart-flutter-patterns/SKILL.mdSao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.
Cách dùng
Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.
Tin nhắn có sẵn để dán
Dành cho Claude Code, Codex hoặc Cursor: chạy lệnh trong thư mục dự án của bạn và skill sẽ được cài đặt.
Tải tệp SKILL.md về và thả vào thư mục skill của agent.
Ví dụ cách nhờ AI
“Làm sao để quản lý trạng thái ứng dụng Flutter của tôi hiệu quả hơn bằng BLoC hoặc Riverpod?”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
Nó đưa ra các đoạn code bạn có thể sao chép và dán, được sắp xếp theo chủ đề như null safety, trạng thái bất biến, quản lý trạng thái và điều hướng.
Nội dung kỹ thuật (SKILL.md gốc)
Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.
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
…
Câu hỏi thường gặp
'Null safety' là gì?
Đây là tính năng của Dart giúp ngăn các lỗi thường gặp khi một biến cần có giá trị nhưng lại trống (null).
'Trạng thái bất biến' nghĩa là gì?
Nghĩa là khi dữ liệu đã được tạo, nó không thể bị thay đổi trực tiếp. Muốn sửa, bạn tạo một phiên bản mới của dữ liệu đó, giúp code dễ đoán hơn.
Các công cụ quản lý trạng thái nào được đề cập?
Những công cụ phổ biến nhất: BLoC/Cubit, Riverpod và Provider.
Chi tiết
Mô tả gốc của tác giả
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
Độ phổ biến
- Sao GitHub
- 280k
- Vị trí xếp hạng
- #161
- Giấy phép
- MIT
- Cập nhật
- 15/10/2026
Bình luận
- …
Thêm skill từ kho mã này
accessibility
280kGiúp agent của bạn tạo giao diện mà ai cũng dùng được, đảm bảo website và app hoạt động tốt với người khuyết tật như người mù hoặc khó vận động.
agent-architecture-audit
280kGiúp agent của bạn kiểm tra xem mọi thứ có hoạt động đúng không, đồng thời tìm và sửa các lỗi trong hệ thống AI để chúng chạy như mong đợi.
agent-eval
280kGiúp agent của bạn so sánh các công cụ lập trình AI khác nhau, đo xem công cụ nào nhanh hơn, rẻ hơn và đáng tin cậy hơn cho từng tác vụ.
agent-harness-construction
280kGiúp agent của bạn hiểu rõ hơn cách thực hiện tác vụ, tối ưu các công cụ và chỉ dẫn mà agent dùng để tăng khả năng thành công.
Skill tương tự
flutter-animating-apps
101kGiúp agent của bạn thêm hiệu ứng hoạt ảnh và chuyển cảnh trong ứng dụng Flutter. Hữu ích để tạo chuyển động trên ứng dụng iOS và Android.
agent-spec-mobile-react-native
81kGiúp agent xây dựng ứng dụng di động cho iPhone và Android bằng React Native, gồm màn hình, điều hướng và module gốc.
orientation
75kGiúp agent của bạn đảm bảo trang hoạt động cả ở chế độ dọc và ngang, gỡ khóa xoay màn hình và thông báo xoay thiết bị đang chặn người dùng xem nội dung.