Sub topic 4
Deciding what is shared
This chapter covers one question that comes up in every feature-first Flutter project: should this code live inside a feature, or in shared code? It assumes you can read Dart imports and exports, know the layer-first and feature-first layouts from earlier chapters, and have a rough idea of what a feature folder holds (presentation, domain, data).
Why the shared folder is the risky part
A feature-first layout works because each feature owns its code and changes stay local. The shared folder is the exception. Every feature may import it, so a change there can break any feature. A shared folder that fills up carelessly turns into a second layer-first project, with utils, helpers, and models folders that everything depends on.
The goal is a small core that changes rarely. Most code should stay in the feature that uses it.
In the layout used throughout this tutorial, shared code sits in two places:
lib/core/holds code that has nothing to do with any one product feature. Examples are network setup, theme, and generic widgets.lib/app/holds the app shell: theMaterialApp, the router, and dependency wiring. It is allowed to import every feature. Features never import it.
lib/
app/
app.dart
router.dart
core/
network/
theme/
widgets/
contracts/
features/
catalog/
cart/What belongs in core
Code is a good candidate for core when it passes all of these checks:
- It has no product vocabulary. A
PrimaryButton, anHttpClientwrapper, or aDebouncerknows nothing about carts or catalogs. ACartBadgedoes. - At least two features use it today. Not "might use it someday".
- It is stable. The reason to change it is a technical one, such as a new logging library. It does not change because a feature's requirements changed.
- It does not import any feature. If a core file imports
features/cart/..., it is feature code in the wrong place.
Typical core contents:
| Folder | Contents | Why it fits |
|---|---|---|
| `core/network` | HTTP client, interceptors, error mapping | Every data layer needs it, and it knows no feature |
| `core/theme` | Colors, text styles, `ThemeData` | App-wide visual identity |
| `core/widgets` | Generic buttons, loading indicators, error views | Presentation building blocks with no business meaning |
| `core/contracts` | Small interfaces shared by features | Lets features cooperate without importing each other |
| `core/utils` | Date formatting, validators | Only if genuinely generic, and kept small |
What stays in the feature
Keep code in a feature when any of these is true:
- It uses a domain model that belongs to that feature (
CartItem,Product). - Only one feature uses it.
- It encodes a business rule, such as "orders over a threshold ship free".
- It is a widget that only makes sense in that feature's screens.
A feature-owned widget used by one other feature is still feature code. The second feature should reach it through the first feature's public file, which later chapters cover. Moving it to core only because two features want it often pulls product vocabulary into shared code.
The rule of three and duplication
Duplication is cheaper than the wrong abstraction. When two features need similar code, you have three honest options:
- Copy it. Each feature can then evolve it independently.
- Wait until a third use appears, then extract it. With three examples you can see which parts are truly common.
- Extract it immediately only if it clearly has no product vocabulary, such as a generic widget.
Copying feels wrong at first, but two features that look alike today often diverge. A shared "user card" used by the profile feature and the chat feature will gain a flag for each, then another, until nobody dares to edit it.
Shared domain models: the hard case
The most common argument about shared code involves models. Suppose both cart and checkout need to know about a cart's item count. There are three choices:
- Put
CartItemincore/models. Quick, but nowcoreknows about carts, and every change toCartItemripples across the app. - Let checkout import the cart feature. This creates a dependency between features, and checkout now depends on cart's internals unless you restrict it to the public file.
- Put a small interface in
core/contractsand let the app shell supply the implementation. Checkout depends only on what it needs.
Option 3 keeps the dependencies pointing at stable, tiny abstractions. It is the approach used in this tutorial:
// lib/core/contracts/cart_summary.dart
abstract interface class CartSummary {
int get itemCount;
}// lib/features/checkout/presentation/checkout_page.dart
import 'package:flutter/material.dart';
import '../../../core/contracts/cart_summary.dart';
class CheckoutPage extends StatelessWidget {
const CheckoutPage({super.key, required this.cart});
final CartSummary cart;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Text('Items: ${cart.itemCount}')),
);
}
}CheckoutPage knows nothing about the cart feature. In a test you pass any object that implements CartSummary. A later chapter shows how the app shell connects the real cart to it.
Note what the contract contains: one getter. A contract that grows to mirror the whole cart model has become the shared model from option 1 with extra steps. Keep contracts to what the consumer needs.
A decision flow
Use this flow when you are unsure where a file goes.
Common mistakes
- A
commonorutilsdumping ground. Names that describe no responsibility attract unrelated files. Name folders after what they do:network,theme,formatting. - Core importing features. This reverses the dependency direction and creates import cycles. If core needs something from a feature, define an interface in core and have the feature implement it.
- Moving code to core too early. Code extracted after one use is a guess about future needs. Extracting later costs a few edits. Un-sharing code costs much more, because you must find every consumer.
- Putting feature state in core. A global
AppStateholding cart, user, and settings makes every feature depend on every other feature's data. Keep state scoped to the feature that owns it. - Treating
applikecore.appmay import features, so features must not importapp. Putting code there that a feature needs creates a cycle.
Moving code between feature and core
Placement decisions are not permanent. A practical routine:
- Start in the feature. Write the code where it is first needed.
- When a second feature needs it, ask the checks above. If it is generic, move it to
coreand update imports. If it is feature-specific, expose it through the feature's public file or write a contract. - After moving, run the analyzer. Broken imports show every consumer, and the fix is mechanical.
Because imports are explicit, Dart's tooling makes moves safe. Use your IDE's move-file refactoring, which rewrites imports for you.
Checking your understanding
Exercise
A formatPrice(double amount) function is used by the catalog and cart features. It formats the number with the user's locale and a currency symbol. Where should it live, and what would change your answer?
Show answer
Put it in core, for example core/formatting/price_formatter.dart. It has no feature-specific model, two features use it today, and its reason to change is technical (locale handling). The answer would change if it started to contain a business rule, such as applying a cart-specific discount. Then that logic belongs in the feature that owns the rule, and only the generic formatting would stay in core.
Exercise
The checkout feature needs to show the number of items in the cart. List one wrong way and one preferred way to give it that information, and give a reason for each.
Show answer
Wrong: move CartItem and the cart repository into core/models. Core would then hold cart vocabulary, and every cart change would ripple through the app. Preferred: define a one-getter CartSummary interface in core/contracts, have checkout depend on it, and let the app shell provide a cart-backed implementation. Checkout then does not import the cart feature and is easy to test with a fake.