agentleFS
VeryGoodOpenSourceVeryGoodOpenSource/vgv-ai-flutter-plugin/skills/layered-architecture/SKILL.md

layered-architecture

Skill168 starsChanged 3 months agoMITView on GitHub

VGV layered monorepo architecture in Flutter: four layers Data, Repository, Business Logic, and Presentation, unidirectional dependency rules, and model transformation across layers. Use when structuring a multi-package Flutter app, creating data or repository packages, defining layer boundaries, or wiring packages in app bootstrap via path dependencies in pubspec.yaml, barrel exports, and RepositoryProvider. Use too when asked to put a domain model, entity, or shared class in an api_client or data package so the repository and app import it from one place, or to add a cross-package dependency the layers forbid. Also use for a new app, from a one-line description like "I'm starting a weather app that reads from a REST API" plus a request to lay out the package structure, project, folder, or directory layout, or asking how to organize an app that talks to a backend, where a file or feature should live, or which package code belongs in. Applies even when the user never says monorepo, layer, or architecture.

2 other projects use a version of this.

Adopted by

Most recently taken up by

The file

Show its rules and text

We split this skill into the rules it gives an agent

20 rules. About 0 are common, 4 are distinctive, and 16 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 16

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    No Flutter imports — use the very_good_cli MCP server create dart_package tool

    line 134
  2. Distinctive:

    No inter-repository dependencies — repositories are isolated

    line 178
  3. Very specific:

    No Flutter SDK — the very_good_cli MCP server create dart_package tool

    line 179
  4. Very specific:

    Add external dependencies to pubspec.yaml (e.g., http, json_annotation)

    line 333
  5. Very specific:

    Create response models in lib/src/models/ with fromJson/toJson

    line 334
  6. Very specific:

    Create barrel file lib/src/models/models.dart exporting all models

    line 335
  7. Very specific:

    Create the package barrel file lib/<name>_api_client.dart exporting src/ contents

    line 337
  8. Very specific:

    Write unit tests in test/ mirroring lib/ structure — see the testing skill

    line 338
  9. Very specific:

    Use very_good_cli MCP server tool test against the package directory — pass directory: 'packages/<name>_api_client' to scope the run

    line 339
  10. Very specific:

    Add path dependencies to data layer packages in pubspec.yaml

    line 344
  11. Very specific:

    Add equatable to dependencies for domain models

    line 345
  12. Very specific:

    Create domain models in lib/src/models/ extending Equatable

    line 346
  13. Very specific:

    Create barrel file lib/src/models/models.dart

    line 347
  14. Distinctive:

    Add transformation logic from response models to domain models

    line 349
  15. Very specific:

    Create the package barrel file lib/<name>_repository.dart

    line 350
  16. Distinctive:

    Write unit tests with mocked data clients — see the testing skill

    line 351
  17. Very specific:

    Add path dependency on the repository package to root pubspec.yaml

    line 355
  18. Very specific:

    Create the repository in main_<flavor>.dart and pass it to App

    line 356
  19. Very specific:

    Add RepositoryProvider.value in App's MultiRepositoryProvider

    line 357
  20. Distinctive:

    Create the Bloc/Cubit with the repository injected — see the bloc skill

    line 358

≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Layered Architecture

Layered monorepo architecture for Flutter apps — four layers organized as independent Dart packages with strict unidirectional dependencies.


Core Standards

Apply these standards to ALL layered architecture work:

  • Four layers — Data, Repository, Business Logic, Presentation — every feature spans exactly these four layers
  • Unidirectional dependencies — Presentation → Business Logic → Repository → Data — never skip or invert a layer
  • Data and Repository layers live in packages/ — each is an independent Dart package with its own pubspec.yaml
  • Business Logic and Presentation live in lib/ — organized by feature within the app
  • Data layer packages contain zero domain/business logic — they must be reusable in unrelated projects
  • No inter-repository dependencies — repositories never import other repositories
  • No Flutter SDK in data or repository packages — scaffold with the very_good_cli MCP server create dart_package tool
  • One repository per domain — user_repository, weather_repository, auth_repository
  • Path dependencies for local packages — never git: or pub version references for packages in the same repo
  • Barrel exports at every package boundary — src/ is never imported directly by consumers
  • Repositories accept data layer dependencies via constructor injection — never instantiate clients internally
  • App bootstrap wires all layers — main_<flavor>.dart creates clients and repositories, provides them via RepositoryProvider
  • Dart 3.13 primary constructors — on the Dart 3.13+ baseline (very_good_core 1.6 / very_good_analysis 11), declare model and widget fields as primary-constructor declaring parameters (class const User(final String id, final String name) extends Equatable) rather than this.field; keep the classic form only below 3.13

Cross-harness fallback. This skill scaffolds and tests packages via the Very Good CLI MCP server. On a host without this plugin's Bash hooks and without that MCP server connected, run the equivalent very_good create dart_package …, very_good packages get, and very_good test commands directly.

Architecture Overview

LayerResponsibilityLocationDepends OnExample
DataExternal communication — API calls, local storage, platform pluginspackages/<name>_api_client/External packages onlyuser_api_client, local_storage_client
RepositoryData orchestration — combines data sources, transforms models, cachespackages/<name>_repository/Data layer packagesuser_repository, weather_repository
Business LogicState management — processes user actions, emits state changeslib/<feature>/bloc/ or lib/<feature>/cubit/Repository layerLoginBloc, ProfileCubit
PresentationUI — widgets, pages, views, layoutlib/<feature>/view/Business Logic layerLoginPage, ProfileView
┌─────────────────────────────────────────────┐
│              Presentation                   │
│          (lib/<feature>/view/)              │
└──────────────────┬──────────────────────────┘
                   │ reads state / dispatches events
┌──────────────────▼──────────────────────────┐
│            Business Logic                   │
│        (lib/<feature>/bloc/)                │
└──────────────────┬──────────────────────────┘
                   │ calls repository methods
┌──────────────────▼──────────────────────────┐
│              Repository                     │
│      (packages/<name>_repository/)          │
└──────────────────┬──────────────────────────┘
                   │ calls data clients
┌──────────────────▼──────────────────────────┐
│               Data                          │
│     (packages/<name>_api_client/)           │
└─────────────────────────────────────────────┘

Monorepo Structure

Features live in lib/, one directory each, split bloc|cubit/ and view/ with a barrel file. Layers live in packages/, one package per data source and one per repository. The second data package and the second repository follow the same shape as the first.

my_app/
├── lib/
│   ├── app/
│   │   ├── app.dart                          # Barrel file
│   │   └── view/
│   │       └── app.dart                      # App widget with MultiRepositoryProvider
│   ├── login/                                # Feature: login
│   │   ├── login.dart                        # Barrel file
│   │   ├── bloc/
│   │   │   ├── login_bloc.dart
│   │   │   ├── login_event.dart
│   │   │   └── login_state.dart
│   │   └── view/
│   │       ├── login_page.dart               # Page provides Bloc
│   │       └── login_view.dart               # View consumes state
│   ├── profile/                              # Feature: profile
│   ├── main_development.dart                 # Flavor entrypoint
│   ├── main_staging.dart
│   └── main_production.dart
├── packages/
│   ├── auth_api_client/                      # Data layer: auth API
│   │   ├── lib/
│   │   │   ├── auth_api_client.dart          # Barrel file
│   │   │   └── src/
│   │   │       ├── auth_api_client.dart
│   │   │       └── models/
│   │   │           ├── models.dart
│   │   │           └── auth_response.dart
│   │   └── pubspec.yaml
│   ├── local_storage_client/                 # Data layer: local storage
│   ├── auth_repository/                      # Repository layer: auth
│   │   ├── lib/
│   │   │   ├── auth_repository.dart          # Barrel file
│   │   │   └── src/
│   │   │       ├── auth_repository.dart
│   │   │       └── models/
│   │   │           ├── models.dart
│   │   │           └── user.dart             # Domain model
│   │   └── pubspec.yaml
│   └── user_repository/                      # Repository layer: user
├── test/
│   └── ...                                   # Mirrors lib/ structure
└── pubspec.yaml                              # Root app pubspec

Data Layer

The data layer handles all external communication. Each data package wraps a single external source (REST API, local database, platform plugin) and exposes typed methods and response models.

Rules:

  • Models represent the external data shape — match the API/storage schema exactly
  • No Flutter imports — use the very_good_cli MCP server create dart_package tool
  • Constructor-inject HTTP clients for testability
  • Response models use fromJson / toJson factories
  • Export everything through a barrel file — never expose src/

Pattern: Data Client Class

Constructor-inject the HTTP client for testability. Return typed response models — never raw JSON.

/// HTTP client for the User API.
class UserApiClient {
  // http.Client injected — tests pass a mock, production gets a real client
  UserApiClient({
    required String baseUrl,
    http.Client? httpClient,
  })  : _baseUrl = baseUrl,
        _httpClient = httpClient ?? http.Client();

  final String _baseUrl;
  final http.Client _httpClient;

  /// Every method returns a typed response model.
  Future<UserResponse> getUser(String userId) async {
    final response = await _httpClient.get(
      Uri.parse('$_baseUrl/users/$userId'),
    );
    if (response.statusCode != 200) {
      throw UserApiException(response.statusCode, response.body);
    }
    return UserResponse.fromJson(
      json.decode(response.body) as Map<String, dynamic>,
    );
  }
}

See worked-example.md for the complete user_api_client package with pubspec, barrel files, response models, and exception class.

Repository Layer

The repository layer orchestrates data sources and exposes domain models. Each repository composes one or more data clients, transforms response models into domain models, and provides a clean API for the business logic layer.

Rules:

  • No inter-repository dependencies — repositories are isolated
  • No Flutter SDK — the very_good_cli MCP server create dart_package tool
  • Domain models live in the repository package — not in data packages
  • Transform data models into domain models — never leak API response shapes upstream
  • Accept all data clients via constructor injection

Pattern: Domain Model + Repository Transformation

Domain models extend Equatable and represent the app's internal data shape — distinct from the API response shape. The repository method transforms between them.

/// Domain model — lives in the repository package, NOT the data package.
/// Fields match the app's needs, not the API schema.
class const User({
  required final String id,
  required final String email,
  required final String displayName,
  final String? avatarUrl,
}) extends Equatable {
  @override
  List<Object?> get props => [id, email, displayName, avatarUrl];
}
/// Repository accepts data client via constructor — never creates its own.
class UserRepository {
  const UserRepository({
    required UserApiClient userApiClient,
  }) : _userApiClient = userApiClient;

  final UserApiClient _userApiClient;

  /// Transforms UserResponse (API shape) → User (domain shape).
  Future<User> getUser(String userId) async {
    final response = await _userApiClient.getUser(userId);
    return User(
      id: response.id,
      email: response.email,
      displayName: response.displayName,
      avatarUrl: response.avatarUrl,
    );
  }
}

See worked-example.md for the complete user_repository package with pubspec, barrel files, and error handling. See model-transformation.md for detailed transformation patterns between data and domain models.

Dependency Graph

Path dependencies in each pubspec.yaml are what enforce the architecture. A data package declares external packages only. A repository package declares a path dependency on its data package. The root app declares repository packages only — data packages arrive as transitive dependencies.

The app never depends on a data package directly. That is the boundary: business logic and presentation cannot bypass the repository layer, because they cannot import past it.

# packages/user_api_client/pubspec.yaml — external packages only
dependencies:
  http: ^1.4.0

# packages/user_repository/pubspec.yaml — path dependency on its data package
dependencies:
  user_api_client:
    path: ../user_api_client

# pubspec.yaml — repository packages only; data packages are transitive
dependencies:
  user_repository:
    path: packages/user_repository

See references/pubspec.md for the three files in full.

Data Flow

Step-by-step walkthrough: user taps "Load Profile" button.

  1. Presentation dispatches event — context.read<ProfileBloc>().add(ProfileLoadRequested(userId: '123'))
  2. Business Logic calls repository — Bloc handler invokes _userRepository.getUser(event.userId) and emits state based on the result
  3. Repository calls data client — UserRepository.getUser delegates to _userApiClient.getUser and transforms the response into a domain User
  4. Data layer communicates with external source — UserApiClient.getUser makes the HTTP request and returns a typed UserResponse
  5. Data flows back up — Presentation rebuilds via BlocBuilder based on the new state
// lib/profile/bloc/profile_bloc.dart
Future<void> _onLoadRequested(
  ProfileLoadRequested event,
  Emitter<ProfileState> emit,
) async {
  emit(const ProfileState.loading());
  try {
    final user = await _userRepository.getUser(event.userId);
    emit(ProfileState.success(user: user));
  } on UserNotFoundException {
    emit(const ProfileState.notFound());
  } catch (_) {
    emit(const ProfileState.failure());
  }
}

App Bootstrap

main_<flavor>.dart constructs every data client and repository, then passes them to the App widget, which exposes them through MultiRepositoryProvider. Flavors change only configuration — base URLs, API keys — never the wiring shape.

// lib/main_development.dart
void main() {
  WidgetsFlutterBinding.ensureInitialized();

  const baseUrl = 'https://api.dev.example.com';

  // Data layer
  final authApiClient = AuthApiClient(baseUrl: baseUrl);
  final userApiClient = UserApiClient(baseUrl: baseUrl);

  // Repository layer
  final authRepository = AuthRepository(authApiClient: authApiClient);
  final userRepository = UserRepository(userApiClient: userApiClient);

  runApp(
    App(
      authRepository: authRepository,
      userRepository: userRepository,
    ),
  );
}

See references/worked-example.md for the full main() and the App widget with MultiRepositoryProvider.

Anti-Patterns

Anti-PatternProblemCorrect Approach
Widget calls API client directlyBypasses Repository and Business Logic layers — no transformation, no state managementWidget dispatches event → Bloc calls Repository → Repository calls API client
Repository imports another repositoryCreates circular or tangled dependency graphs — breaks independent testabilityEach repository is self-contained; combine data at the Bloc level if needed
Domain models in data layerCouples external API shape to internal domain — API changes break the entire appData layer has response models; Repository layer has domain models with transformation
Business logic in repositoryRepository becomes untestable monolith mixing orchestration with rulesRepository transforms data; Bloc/Cubit contains all business rules
git: or pub version for local packagesBreaks monorepo — changes require publish/push cycles instead of instant local editsUse path: dependencies for all packages within the monorepo
Flutter imports in data/repository packagesPrevents packages from being used in Dart-only contexts (CLI tools, servers)Scaffold with the very_good_cli MCP server create dart_package tool — no Flutter SDK dependency
One giant repository for everythingGod-object with too many responsibilities — impossible to test in isolationOne repository per domain boundary (user_repository, settings_repository)
Importing src/ directlyBreaks encapsulation — consumers depend on internal structureExport public API through barrel files; import the package, never src/ paths

Common Workflows

Adding a New Data Source

  1. Scaffold the package with the very_good_cli MCP server create dart_package tool: <name>_api_client --output-directory packages
  2. Add external dependencies to pubspec.yaml (e.g., http, json_annotation)
  3. Create response models in lib/src/models/ with fromJson/toJson
  4. Create barrel file lib/src/models/models.dart exporting all models
  5. Implement the client class in lib/src/<name>_api_client.dart
  6. Create the package barrel file lib/<name>_api_client.dart exporting src/ contents
  7. Write unit tests in test/ mirroring lib/ structure — see the testing skill
  8. Use very_good_cli MCP server tool test against the package directory — pass directory: 'packages/<name>_api_client' to scope the run

Adding a New Repository

  1. Scaffold the package with the very_good_cli MCP server create dart_package tool: <name>_repository --output-directory packages
  2. Add path dependencies to data layer packages in pubspec.yaml
  3. Add equatable to dependencies for domain models
  4. Create domain models in lib/src/models/ extending Equatable
  5. Create barrel file lib/src/models/models.dart
  6. Implement the repository class with constructor-injected data clients
  7. Add transformation logic from response models to domain models
  8. Create the package barrel file lib/<name>_repository.dart
  9. Write unit tests with mocked data clients — see the testing skill

Connecting a Repository to a Feature

  1. Add path dependency on the repository package to root pubspec.yaml
  2. Create the repository in main_<flavor>.dart and pass it to App
  3. Add RepositoryProvider.value in App's MultiRepositoryProvider
  4. Create the Bloc/Cubit with the repository injected — see the bloc skill
  5. Build the Page/View with BlocProvider and BlocBuilder — see the bloc skill

Additional Resources

  • Complete worked example and pubspec reference
  • Data flow walkthrough — the request path with code at each layer
  • Model transformation patterns — data model vs domain model conversion
  • Package-level testing — testing data clients and repositories in isolation
  • For Bloc/Cubit patterns and Page/View separation — see the bloc skill
  • For project scaffolding use the very_good_cli MCP server create dart_package tool
  • For testing data clients, repositories, and Blocs — see the testing skill

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.