К основному содержанию
скилл CX Codex

architecture-feature-first — скилл для Claude Code

Скилл architecture-feature-first задаёт слоистую feature-first архитектуру для Flutter: где лежит UI, где данные и когда нужен доменный слой.

MIT ★ 674 обновлён 2026-10-29

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add evanca/flutter-ai-rules
/plugin install flutter-ai-skills@flutter-ai-rules
Открыть на GitHub

Что делает architecture-feature-first

Скилл описывает, как делить Flutter-приложение на UI-слой, слой данных и опциональный доменный слой с use cases, и как раскладывать файлы не по типу, а по фиче — всё, что относится к auth или profile, лежит в одной папке с подкаталогами data/, ui/ и, если нужно, domain/.

Он не привязан к конкретному стейт-менеджменту: держатель бизнес-логики в UI-слое может называться ViewModel, Cubit, Controller или Notifier, правила слоёв одинаковы для всех. Репозиторий — единственный источник правды для данных, UI не может менять их напрямую и не обращается к сервисам, минуя репозиторий.

Отдельно расписан порядок внедрения зависимостей: сервисы передаются в репозитории через конструктор, репозитории — в держатели логики, а регистрация идёт через DI-контейнер вроде get_it. Для простых CRUD-приложений доменный слой с use cases скилл советует не добавлять.

Какие задачи решает

  • разложить код Flutter-проекта по фичам, а не по типу файлов
  • решить, в каком слое должна жить конкретная логика
  • настроить передачу зависимостей через конструкторы для репозиториев и держателей логики
  • понять, когда нужен доменный слой с use cases, а когда он лишний
  • описать роли View, Repository и Service при переходе на слоистую архитектуру

Примеры запросов агенту

  • Спроектируй структуру папок для новой фичи profile по feature-first подходу
  • Реши, в какой слой вынести логику кэширования для AuthRepository
  • Опиши, как связать AuthRepository и AuthApiService через конструктор

Как установить architecture-feature-first

1Через маркетплейс плагинов

/plugin marketplace add evanca/flutter-ai-rules
/plugin install flutter-ai-skills@flutter-ai-rules

Команда ставит плагин flutter-ai-skills целиком, со всеми его скиллами

2Через Skills CLI (Vercel)

npx skills add evanca/flutter-ai-rules --skill architecture-feature-first -a claude-code

3Вручную: положить файлы

~/.claude/skills/architecture-feature-first/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/architecture-feature-first/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы об architecture-feature-first

Как установить architecture-feature-first в Claude Code?

Выполните /plugin marketplace add evanca/flutter-ai-rules, затем /plugin install flutter-ai-skills@flutter-ai-rules.

Что делает architecture-feature-first?

Скилл задаёт правила слоистой feature-first архитектуры для Flutter: разделение на UI, данные и домен, структуру папок по фичам и порядок внедрения зависимостей между репозиториями и держателями логики.

Для какого стейт-менеджмента подходит architecture-feature-first?

Скилл не завязан на конкретный подход: держатель бизнес-логики может называться ViewModel, Cubit, Controller или Notifier, а правила слоёв применяются одинаково.

Исходный текст

SKILL.md · MIT
---
name: architecture-feature-first
description: "Use when creating a feature, designing folder structure, adding repositories/services/view models, wiring dependency injection, or deciding which layer owns logic."
license: MIT
---

# Flutter Architecture — Feature-First Skill

This skill defines how to design, structure, and implement Flutter applications using the recommended **layered architecture** with **feature-first** file organization.

It is **state management agnostic**: the business logic holder in the UI layer may be named ViewModel, Controller, Cubit, Bloc, Provider, or Notifier — depending on the chosen state management approach. The architectural rules apply equally to all of them.

## When to Use

Use this skill when:

* Designing the folder/file structure of a new Flutter app or feature.
* Creating a new View, ViewModel, Repository, or Service.
* Deciding which layer owns a piece of logic.
* Wiring dependency injection between components.
* Adding a domain (logic) layer for complex business logic.
* Refactoring an existing app from type-first to feature-first organization.

---

## 1. Layers

Separate every app into a **UI Layer** and a **Data Layer**. Add a **Logic (Domain) Layer** between them only for complex apps.

```
┌──────────────────────────────────────────────────────────────┐
│   UI Layer    │  Views + business logic holders              │
│               │  (ViewModel / Cubit / Controller / Provider) │
├──────────────────────────────────────────────────────────────┤
│  Logic Layer  │  Use Cases / Interactors  (optional)         │
├──────────────────────────────────────────────────────────────┤
│   Data Layer  │  Repositories + Services                     │
└──────────────────────────────────────────────────────────────┘
```

**Rules:**
- Only adjacent layers may communicate. The UI layer must never access a Service directly.
- The Logic layer is added **only** when business logic is too complex for the business logic holder or is reused across multiple screens.
- Data changes always happen in the Data layer (SSOT = Repository). No mutation in UI or Logic layers.
- Follow unidirectional data flow: state flows **down** (Data → UI), events flow **up** (UI → Data).

---

## 2. Feature-First File Structure

Organize code by **feature**, not by type. Group all layers belonging to one feature together in a single directory.

### Sample directory structure

```
lib/
├── app.dart
├── main.dart
├── core/                          # Shared utilities, theme, DI setup
│   ├── di/
│   │   └── service_locator.dart
│   ├── theme/
│   │   └── app_theme.dart
│   └── network/
│       └── api_client.dart
├── features/
│   ├── auth/
│   │   ├── data/
│   │   │   ├── auth_repository.dart
│   │   │   └── auth_api_service.dart
│   │   ├── domain/                # Optional — only for complex logic
│   │   │   └── login_usecase.dart
│   │   └── ui/
│   │       ├── auth_viewmodel.dart
│   │       ├── login_screen.dart
│   │       └── widgets/
│   │           └── login_form.dart
│   └── profile/
│       ├── data/
│       │   ├── profile_repository.dart
│       │   └── profile_api_service.dart
│       └── ui/
│           ├── profile_viewmodel.dart
│           └── profile_screen.dart
└── shared/                        # Shared widgets, models, extensions
    ├── models/
    │   └── user.dart
    └── widgets/
        └── loading_indicator.dart
```

Each feature directory contains the files needed for that feature, named according to the chosen state management approach:

| Approach | Business logic holder file |
|---|---|
| MVVM / ChangeNotifier | `*_viewmodel.dart` / `*_controller.dart` |
| BLoC | `*_cubit.dart` / `*_bloc.dart` |
| Provider / Riverpod | `*_provider.dart` / `*_notifier.dart` |

---

## 3. Component Responsibilities

### View
- Describes how to present data to the user; keep logic minimal and only UI-related.
- Passes events to the business logic holder in response to user interactions.
- Extract reusable widgets into separate components within a `widgets/` subdirectory.
- Use `StatelessWidget` when possible; keep build methods simple.

### Business Logic Holder (ViewModel / Cubit / Controller / Provider)
- Contains logic to convert app data into UI state and maintains current state needed by the view.
- Exposes callbacks (commands) to the View and retrieves/transforms data from repositories.

```dart
class AuthViewModel extends ChangeNotifier {
  final AuthRepository _authRepo;
  AuthViewModel(this._authRepo);

  bool _isLoading = false;
  bool get isLoading => _isLoading;

  String? _error;
  String? get error => _error;

  Future<bool> login(String email, String password) async {
    _isLoading = true;
    _error = null;
    notifyListeners();
    try {
      await _authRepo.login(email, password);
      return true;
    } catch (e) {
      _error = e.toString();
      return false;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }
}
```

### Repository
- Single Source of Truth (SSOT) for a given type of model data.
- The only class allowed to mutate its data; all other classes read from it.
- Handles caching, error handling, and data refresh logic.
- Transforms raw data from services into domain models.

### Service
- Wraps API endpoints and exposes asynchronous response objects.
- Isolates data-loading and holds no state.

---

## 4. Domain Layer (Use Cases)

Introduce use cases/interactors **only** when:
- Logic is complex or does not fit cleanly in the UI or Data layers.
- Logic is reused across multiple business logic holders or merges data from multiple repositories.

Do not add a domain layer for simple CRUD apps.

---

## 5. Dependency Injection

Use dependency injection to provide components with their dependencies, enabling testability and flexibility.

- Supply repositories to business logic holders via constructors.
- Supply services to repositories via constructors.
- Define abstract interfaces so implementations can be swapped without changing consumers.

```dart
// In service_locator.dart — register dependencies at startup
void setupDependencies() {
  final apiClient = ApiClient();

  // Services
  final authService = AuthApiService(apiClient);
  final profileService = ProfileApiService(apiClient);

  // Repositories
  final authRepo = AuthRepository(authService);
  final profileRepo = ProfileRepository(profileService);

  // Register with your DI framework (get_it, provider, riverpod, etc.)
  getIt.registerSingleton<AuthRepository>(authRepo);
  getIt.registerSingleton<ProfileRepository>(profileRepo);
}
```

---

## 6. Workflow: Add a New Feature

1. **Create the `features/<name>/` directory** with `data/`, `ui/`, and optionally `domain/` subdirectories.
2. **Implement the Service** — wrap the API endpoints in `data/<name>_api_service.dart`.
3. **Implement the Repository** — inject the Service, add caching/error handling in `data/<name>_repository.dart`.
4. **Implement the ViewModel** — inject the Repository, expose UI state and commands in `ui/<name>_viewmodel.dart`.
5. **Implement the View** — bind to the ViewModel, render state, dispatch events in `ui/<name>_screen.dart`.
6. **Register in DI** — add the new Service, Repository, and ViewModel to the service locator.
7. **Verify** — confirm the View never accesses the Service directly and data flows unidirectionally.

---

## References

- [Flutter app architecture guide](https://docs.flutter.dev/app-architecture/guide)
- [Architecture case study (Compass app)](https://docs.flutter.dev/app-architecture/case-study)
- [Architecture recommendations](https://docs.flutter.dev/app-architecture/recommendations)

© Ivanna Kaceviča · MIT · evanca/flutter-ai-rules

Похожие скиллы

Все скиллы по теме «Мобильная разработка» →
flutter-architecture Stanislav [MADTeacher] Chernyshev Скилл flutter-architecture для проектирования и ревью архитектуры Flutter-приложений: слои, MVVM, feature-first структура, DI и паттерны вроде Result и Command. CX Codex +1 1 700установок flutter-apply-architecture-best-practices flutter Скилл flutter-apply-architecture-best-practices для Claude Code раскладывает Flutter-приложение по слоям UI, Logic и Data. Описывает архитектуру нового проекта и рефакторинг кода. CX Codex +1 47 000установок swift-architecture-skill efremidze Скилл swift-architecture-skill для Claude Code помогает выбрать и применить архитектуру для SwiftUI- или UIKit-кода. Он включается при проектировании, рефакторинге и ревью функций и модулей. CX Codex +1 2 100установок flutter-development-guidelines-cursorrules-prompt-file PatrickJS flutter-development-guidelines-cursorrules-prompt-file — правило Cursor для структуры Flutter-проекта, нейминга и стиля Dart. Включается при работе с файлами **/*.dart. CX Codex +1 ★ 41 178звёзд репо flutter sanjeed5 Правило задаёт Cursor единый стиль Flutter-кода: форматирование, линты, слои MVVM и Riverpod. Агент перестаёт спорить о стиле и ловит типовые ошибки раньше. CX Codex +1 ★ 3 589звёзд репо ios-uikit-architecture TheBushidoCollective Скилл ios-uikit-architecture с паттернами архитектуры UIKit: MVVM, MVC, координаторы, dependency injection и способы встроить SwiftUI в UIKit-приложение. Пригодится при разработке iOS-приложений на UIKit. CX Codex +1 145установок

Из того же набора39

Весь набор →
firebase-app-check Скилл помогает внедрить Firebase App Check во Flutter: выбрать провайдеров, настроить debug-токены и включить проверку запросов. CX Codex +1 ★ 674звёзд репо flutter-best-practices Скилл flutter-best-practices для Claude Code задаёт правила Flutter и Dart: слои, структура фич, виджеты и тесты. Агент читает нужный файл-справочник под задачу. CX Codex +1 ★ 674звёзд репо flutter-app-architecture Скилл flutter-app-architecture задаёт правила многослойной архитектуры Flutter-проекта: MVVM, репозитории, сервисы и однонаправленный поток данных. CX Codex +1 ★ 674звёзд репо riverpod Скилл помогает писать Flutter- и Dart-код с Riverpod: настраивать провайдеры, управлять их жизненным циклом и проверять их тестами. Пригодится при работе с состоянием приложения. CX Codex +1 ★ 674звёзд репо inclusive-design Скилл inclusive-design помогает проектировать интерфейсы с учётом медленного интернета, дешёвых смартфонов, нестандартных имён и низкого цифрового опыта. Не заменяет WCAG. CX Codex +1 ★ 674звёзд репо firebase-database Скилл firebase-database помогает проектировать структуру Firebase Realtime Database и работать с чтением, записями, синхронизацией и правилами доступа в приложениях Flutter. CX Codex +1 ★ 674звёзд репо dart-3-updates Скилл dart-3-updates для Claude Code и Codex учит ИИ писать switch-выражения, паттерны, records и modern Dart вместо старых if-else цепочек. Помогает при рефакторинге кода под Dart 3 и выборе между records и классами. CX Codex +1 ★ 674звёзд репо effective-dart Скилл effective-dart задаёт правила чистого кода на Dart и Flutter: стиль имён, явные типы, оформление документации и структуру тестов. CX Codex +1 ★ 674звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой