Sub topic 1
Why Structure Matters as an App Grows
A Flutter app starts small. A few screens sit in one folder and everything fits in your head. After a year, the same folders hold dozens of screens, services, and models, and changing one thing breaks something unrelated. This chapter explains why the way you arrange folders matters, and how to decide what belongs where.
Prerequisites
You should already be comfortable with:
- Building Flutter apps with widgets and navigation
- Dart imports and the
exportdirective - One state management approach, such as
providerorriverpod - The basic idea of the repository pattern
Layer-first versus feature-first
A layer-first project groups files by technical role:
lib/
presentation/
cart_page.dart
catalog_page.dart
domain/
cart_item.dart
data/
cart_api.dartA feature-first project groups files by product feature:
lib/
features/
cart/
catalog/Layer-first works for small apps. Once a change to the cart touches four top-level folders, the folders stop helping you find things.
What goes inside a feature folder
Each feature holds its own presentation, domain, and data code. The domain layer defines the interface, and the data layer implements it:
// lib/features/cart/domain/cart_repository.dart
abstract interface class CartRepository {
Future<List<String>> loadItems();
}Presentation code depends only on CartRepository, so you can swap the data source without editing any screen.
Deciding what is shared
Put code in core only when two or more features need it.
| Code | Where it belongs |
|---|---|
| A price formatter used by cart and checkout | `core` |
| A cart item model used only by cart | `features/cart` |
| A button style used across the app | `core` |
Exercise
A checkout feature needs the number of items in the cart. Should checkout import the cart feature directly?
Show answer
No. Checkout should depend on a small interface in core, such as CartSummary, and the app shell should supply a cart-backed implementation. This keeps the two features independent.