0Pricing
Flutter Mobile Development · 강의

기능 우선 폴더 구조 및 Melos 모노레포

기능을 독립적인 패키지로 구성하고 Melos 모노레포로 관리합니다.

기능 우선 폴더 구조 및 Melos 모노레포은(는) CoddyKit의 무료 Flutter Mobile Development 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Flutter Mobile Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Feature-First?

As a Flutter app grows, the classic layer-first structure (top-level screens/, widgets/, models/, services/) starts to hurt. To touch one feature you jump across five folders, and unrelated teams collide in the same files.

Feature-first flips this: the top level is organized by business capability (auth, cart, profile), and each feature owns its own layers internally.

  • High cohesion — everything for a feature lives together.
  • Low coupling — features depend on contracts, not each other's internals.
  • Scalability — a feature can later be extracted into its own package with almost no churn.

Anatomy of a Feature Folder

Inside lib/features/<feature>/ we mirror Clean Architecture's three layers. The domain layer is pure Dart with no Flutter or plugin imports, which is exactly what makes a feature easy to extract later.

A typical auth feature:

  • data/ — DTOs, data sources, repository implementations.
  • domain/ — entities, repository interfaces, use cases.
  • presentation/ — widgets, pages, state (BLoC/Riverpod).
lib/
├── core/                  // shared cross-cutting code
│   ├── error/
│   └── network/
└── features/
    └── auth/
        ├── data/
        │   ├── models/
        │   ├── datasources/
        │   └── repositories/
        ├── domain/
        │   ├── entities/
        │   ├── repositories/
        │   └── usecases/
        └── presentation/
            ├── bloc/
            ├── pages/
            └── widgets/

The Domain Layer Is Pure Dart

The key discipline that makes a feature portable: the domain layer imports nothing from Flutter or plugins. Entities are plain immutable Dart classes, and repository contracts are abstract interfaces.

Because this code has no framework dependencies, it is trivially unit-testable and can run on any Dart VM — including an online judge.

// domain/entities/user.dart
class User {
  final String id;
  final String email;
  const User({required this.id, required this.email});
}

// domain/repositories/auth_repository.dart
abstract class AuthRepository {
  Future<User> signIn(String email, String password);
}

void main() {
  const user = User(id: '1', email: 'ada@example.com');
  print('Loaded ${user.email}');
}

Use Cases Encode Business Rules

A use case is a single-responsibility object that orchestrates one application action. It depends only on the repository interface, never on its implementation. This keeps the presentation layer dumb and the rules testable.

The common Flutter convention is to give each use case a call method so it can be invoked like a function.

// domain/usecases/sign_in.dart
class User {
  final String email;
  const User(this.email);
}

abstract class AuthRepository {
  Future<User> signIn(String email, String password);
}

class SignIn {
  final AuthRepository repository;
  const SignIn(this.repository);

  Future<User> call(String email, String password) {
    if (!email.contains('@')) {
      throw ArgumentError('Invalid email');
    }
    return repository.signIn(email, password);
  }
}

class FakeRepo implements AuthRepository {
  @override
  Future<User> signIn(String email, String password) async => User(email);
}

void main() async {
  final signIn = SignIn(FakeRepo());
  final user = await signIn('ada@example.com', 'pw');
  print('Signed in: ${user.email}');
}

From Folders to Packages

Feature-first folders are a great first step, but folders don't enforce boundaries — any file can still import any other. The next level is to make each feature a real Dart package with its own pubspec.yaml.

Now the compiler enforces isolation: a package can only use what it explicitly declares as a dependency. This is where a monorepo comes in — many packages, one repository.

  • packages/feature_auth/
  • packages/feature_cart/
  • packages/core/
  • apps/mobile/ (the runnable Flutter app that wires features together)

What Is Melos?

Melos is a CLI tool for managing Dart/Flutter monorepos with multiple packages. It solves the pain of running pub get, tests, and version bumps across dozens of packages.

  • Bootstrap — links local packages together and resolves all dependencies in one command.
  • Scripting — define named scripts that run across every package.
  • Versioning — conventional-commit based version bumps and changelogs.

You install it once globally and configure it per repository with a melos.yaml.

dart pub global activate melos

# from the monorepo root
melos bootstrap   # or: melos bs

Configuring melos.yaml

At the repo root, melos.yaml declares the workspace name and where packages live (glob patterns). Modern Melos (3+) also supports declaring the workspace inside the root pubspec.yaml, but a dedicated file remains common.

The packages globs tell Melos which folders are managed members of the monorepo.

# melos.yaml
name: shop_workspace

packages:
  - apps/**
  - packages/**

command:
  bootstrap:
    usePubspecOverrides: true

Wiring Local Path Dependencies

Inside the app, you depend on local feature packages by name. With usePubspecOverrides: true, Melos injects the local path: overrides automatically during bootstrap, so your committed pubspec.yaml can reference versions while local development still uses source.

The result: editing a file in feature_auth is instantly visible to the app — no publishing, no copy-paste.

# apps/mobile/pubspec.yaml
name: mobile
dependencies:
  flutter:
    sdk: flutter
  feature_auth: ^1.0.0
  feature_cart: ^1.0.0
  core: ^1.0.0

# Melos generates pubspec_overrides.yaml on bootstrap:
# dependency_overrides:
#   feature_auth:
#     path: ../../packages/feature_auth

Defining Workspace Scripts

The biggest day-to-day win is scripts. You define a command once and run it across every package that matches a filter. This replaces brittle shell loops.

Common filters include --dir-exists=test (only packages that have tests) and --depends-on=core (only packages depending on a given package).

# melos.yaml
scripts:
  analyze:
    run: melos exec -- dart analyze .
    description: Analyze every package.

  test:
    run: melos exec --dir-exists=test -- flutter test
    description: Run tests only where a test/ dir exists.

# usage:
#   melos run analyze
#   melos run test

Keeping Features Decoupled

Packages enforce boundaries, but you still must design the contracts. The rule of thumb:

  • Features never import each other directly.
  • Shared contracts and primitives live in a low-level core package that everything may depend on.
  • Cross-feature navigation goes through an abstraction (a router or an event bus) injected at the app level.

This dependency direction — features → core, app → features — keeps the graph acyclic. A cycle between two feature packages will fail to resolve, which is a useful early warning.

// packages/core/lib/src/app_route.dart  (shared contract)
abstract class AppRouter {
  void goToCart();
  void goToProfile();
}

// feature_auth depends on `core`, never on feature_cart.
class LoginController {
  final AppRouter router;
  const LoginController(this.router);

  void onLoginSuccess() => router.goToCart();
}

void main() => print('Auth depends on core, not on cart.');

A Typical Developer Workflow

Putting it together, the daily loop in a Melos monorepo is short and uniform regardless of how many packages you have:

  • melos bootstrap after pulling new changes to relink packages.
  • melos run analyze and melos run test in CI and locally.
  • melos version to bump changed packages from conventional commits.

Because the app is the only Flutter-runnable target and features are plain packages, your CI can test domain logic on the pure Dart VM (fast) and only spin up Flutter for presentation tests.

# clone + first run
melos bootstrap
melos run analyze
melos run test

# ship a release
melos version          # bumps + changelogs from commits
cd apps/mobile && flutter build apk

Quick Check

You have a Melos monorepo with feature_auth and feature_cart packages. After login, auth needs to navigate the user to the cart screen. What is the cleanest way to keep the dependency graph acyclic?

Recap

You learned how to scale a Flutter codebase from folders to packages:

  • Feature-first structure groups code by business capability, each feature mirroring data/domain/presentation layers.
  • The domain layer stays pure Dart, making it portable and easy to extract.
  • Promoting features to Dart packages lets the compiler enforce boundaries that folders cannot.
  • Melos manages the resulting monorepo: bootstrap links packages, scripts run commands across all of them, and version automates releases.
  • Keep the graph acyclic: features depend on core, the app depends on features, and cross-feature concerns go through shared contracts.

자주 묻는 질문

“기능 우선 폴더 구조 및 Melos 모노레포” 강의는 무료인가요?

네 — “기능 우선 폴더 구조 및 Melos 모노레포” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Flutter Mobile Development 강의 전체를 잠금 해제할 수 있습니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.

“기능 우선 폴더 구조 및 Melos 모노레포”에서 뭘 배우나요?

기능을 독립적인 패키지로 구성하고 Melos 모노레포로 관리합니다. 브라우저에서 직접 실행하는 실습 코드로 Flutter Mobile Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Flutter Mobile Development을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Flutter Mobile Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“기능 우선 폴더 구조 및 Melos 모노레포” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Flutter Mobile Development 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Flutter Mobile Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 도메인, 데이터 및 프레젠테이션 계층의 경계
  2. get_it 및 injectable을 활용한 의존성 주입
  3. 기능 우선 폴더 구조 및 Melos 모노레포
  4. Either, 실패 유형 및 함수형 오류 처리
← Flutter Mobile Development(으)로 돌아가기