/flutter:value-objects-money-and-unitsfrom Flutter Skills
Enforces a pure-Dart value-object core storing money as integer minor units keyed to each currency's real ISO-4217 exponent, physical amounts as SI whole units, and timestamps as UTC. Forbids double/num money, cross-currency arithmetic, and hardcoded 100. Routes all money division through a largest-remainder allocate() primitive.
Ships in Flutter Skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Store every quantity once, in one canonical form, and convert only when shown or exported. Money is integer minor units plus a currency; physical quantities are whole SI base units; time is UTC. This is what lets a user flip any display preference (currency symbol, unit system, locale) without corrupting one stored row, and lets "sum of parts == whole" be structural, not hoped-for.
This core is pure Dart — no flutter/*, no intl, no dart:io, no plugins.
Formatting and digit normalization happen upstream/downstream, not here. These
value objects live in lib/core/, the sanctioned pure-foundation layer (see
project-structure-and-packages) — never a utils//common//shared/ grab-bag.
Read the reference for the task at hand:
references/allocate-and-splitting.md — the largest-remainder allocate()
primitive, its invariants, the two-rounding-sites trap, edge policies, verified
test vectors, and the subtotal→tax→tip split pipeline.references/canonical-storage.md — the ISO-4217 exponent rule, the SI unit
tables, decimal-based parsing, the cents-accumulator for keypad input,
rounding discipline, and the Clock-injected dated-rate / staleness engine.references/domain-model.md — value-type modelling: relationships as id links,
derive-don't-store, one currency per aggregate, immutable state with value
equality.Run scripts/check-money-violations.sh and scripts/verify-core.sh before a PR.
int minor units + a Currency — NEVER double/num/REAL.
Binary floats cannot represent 0.01; drift silently corrupts totals the user
can never re-derive. No money API accepts or returns double.* 100, / 100, or "2 decimals". Exponent is 0 for JPY/VND,
2 for USD/EUR, 3 for KWD/BHD/OMR. A hardcoded 100 is a 100× error for a
0-exponent currency and a 10× error for a 3-exponent one. Route through
currency.minorPerMajor.Currency.tryParse returns null
and the caller emits a Failure.Money of different currencies is a category error — throw
(programmer error) or convert through the FX layer first. Keep currency a
fact of the enclosing aggregate so Money arithmetic never has to guard it.allocate(amount, weights)
primitive. Shared items, tax proration, tip proration, discounts — all one
rounding path, so "parts sum to the whole to the exact minor unit" is proven
once and tested once.allocate() AND percent→minor-units.
Round a percentage to integer minor units once before feeding allocate().
A naive double percent is a classic off-by-a-cent bug that allocate
coverage will not catch.allocate() a
known integer total and let the parts absorb the residual.id links, not embedded copies. Give every
entity an explicit final id (e.g. a UUID). Editing a price then leaves
assignments intact and deleting a participant just drops them from link sets.int metres / millilitres / minutes); time is a UTC DateTime.
.from<DisplayUnit> factories round into canonical; to<DisplayUnit>()
getters return a double used only at the presentation edge.int.parse/double.parse/Decimal.parse on raw localized input — it
throws on Eastern-Arabic numerals. Fold upstream (see i18n-rtl-l10n).decimal; round ONCE with an explicit mode at the boundary.
Use package:decimal for exact division/parsing, apply an explicit
RoundingMode (default half-even/banker's) once at the parse or final-total
boundary — never on intermediate sums (accumulates bias).package:clock's Clock; NEVER call DateTime.now(), never roll a
bespoke ClockService. Every time-reading class in this pure core takes a
Clock constructor arg; Riverpod/feature code injects the same Clock
through a clockProvider (see service-boundary-and-native) so the two
vocabularies compose. Fixed clocks / fake_async then make time-dependent
logic deterministic in tests.decimal and
clock. Formatting lives in the presentation layer; storage in the data layer.Widgets and repositories exchange value objects, never raw ints or strings.
| Quantity | Canonical storage | Type | Never store |
|---|---|---|---|
| Money | integer minor units + Currency | int | double, formatted string |
| Distance | whole metres | int | km, miles |
| Volume | whole millilitres | int | litres, gallons |
| Duration | whole minutes (or Duration) | int | hours as double |
| Timestamp | UTC ISO-8601 instant | DateTime (UTC) | local time |
/// ISO-4217 minor-unit exponents. Explicit table — NEVER default to 2.
enum Currency {
jpy('JPY', 0), vnd('VND', 0),
usd('USD', 2), eur('EUR', 2), gbp('GBP', 2),
kwd('KWD', 3), bhd('BHD', 3), omr('OMR', 3);
const Currency(this.code, this.exponent);
final String code;
final int exponent;
/// 10^exponent — minor units per major unit. The ONLY scaling source.
int get minorPerMajor => switch (exponent) {
0 => 1,
2 => 100,
3 => 1000,
_ => throw StateError('unsupported exponent $exponent for $code'),
};
static Currency? tryParse(String code) {
// Plain loop, not `firstOrNull` (a package:collection extension) — keeps the
// core dependency-free beyond `decimal`.
for (final c in Currency.values) {
if (c.code == code) return c;
}
return null;
}
}
/// Money is (integer minor units) + (currency). No floats, ever.
final class Money implements Comparable<Money> {
const Money(this.minorUnits, this.currency);
final int minorUnits; // e.g. 12345 with KWD == 12.345 KWD
final Currency currency;
Money operator +(Money o) => currency == o.currency
? Money(minorUnits + o.minorUnits, currency)
: throw ArgumentError('currency mismatch: $currency vs ${o.currency}');
@override
int compareTo(Money o) {
assert(currency == o.currency, 'compare across currencies is a bug');
return minorUnits.compareTo(o.minorUnits);
}
@override
bool operator ==(Object o) =>
o is Money && o.minorUnits == minorUnits && o.currency == currency;
@override
int get hashCode => Object.hash(minorUnits, currency);
}
Physical value objects follow the identical shape — an integer canonical field,
rounding .from<Unit> factories, and edge-only to<Unit>() getters. See
references/canonical-storage.md and examples/money.dart.
allocate()Every time money is split, it goes through this integer largest-remainder (Hamilton) primitive. Never divide money any other way.
/// Splits [amount] minor units across [weights], guaranteeing the parts sum
/// EXACTLY to [amount]. Deterministic ascending-index tie-break; residual < n.
/// Negative amount mirrors and negates (discounts/refunds); zero weight-sum
/// falls back to equal weights; empty weights returns [] — money math must
/// never throw into the UI.
List<int> allocate(int amount, List<int> weights) {
final n = weights.length;
if (n == 0) return const [];
if (amount < 0) return allocate(-amount, weights).map((s) => -s).toList();
final sanitized = [for (final w in weights) w < 0 ? 0 : w];
final weightSum = sanitized.fold(0, (a, b) => a + b);
final w = weightSum == 0 ? List.filled(n, 1) : sanitized;
final total = weightSum == 0 ? n : weightSum;
final shares = List<int>.filled(n, 0);
final remainders = <({int remainder, int index})>[];
var distributed = 0;
for (var i = 0; i < n; i++) {
final product = amount * w[i]; // multiply FIRST, then ~/ and % — no float
final floorShare = product ~/ total;
shares[i] = floorShare;
distributed += floorShare;
remainders.add((remainder: product % total, index: i));
}
var leftover = amount - distributed; // always in 0 ..< n
remainders.sort((a, b) => a.remainder != b.remainder
? b.remainder.compareTo(a.remainder)
: a.index.compareTo(b.index));
for (var k = 0; leftover > 0; k++, leftover--) {
shares[remainders[k].index] += 1;
}
assert(shares.fold(0, (a, b) => a + b) == amount, 'allocate must be exact');
return shares;
}
Verified vectors (assert these in a test):
allocate(1001,[1,1,1]) == [334,334,333] ·
allocate(660,[1584,4033,1933]) == [138,353,169] ·
allocate(1510,[1584,4033,1933]) == [317,807,386].
The split pipeline layers allocate() in passes — item subtotals, then
allocate(taxMinor, subtotals), then allocate(tipMinor, subtotals) — so every
whole-bill figure is distributed and the per-participant finals sum to the grand
total exactly. Full pipeline, edge policies, and the percent→minor-units rounding
site are in references/allocate-and-splitting.md and examples/allocate.dart.
Input must already be ASCII-normalized upstream. Parse with decimal (no binary
error), scale by the currency's exponent, round once.
/// Caller MUST have normalized digits + separators to ASCII first.
Money moneyFromMajorString(String ascii, Currency c) {
final scaled = (Decimal.parse(ascii) * Decimal.fromInt(c.minorPerMajor))
.round(); // exact; Decimal has no binary-float error
return Money(scaled.toBigInt().toInt(), c);
}
For a numeric keypad with no fixed decimal key, accumulate digits into minor
units directly and never touch a locale decimal separator — see
references/canonical-storage.md.
Totals are computed on read from items + weights; a stored total is a drift bug.
Any time-dependent value object (a dated rate, a staleness band, an expiry) takes
an injected Clock so tests are deterministic.
final class RateSnapshot {
const RateSnapshot(this._clock);
final Clock _clock;
int ageDays(DateTime asOfUtc) => _clock.now().difference(asOfUtc).inDays;
}
// prod: RateSnapshot(const Clock()); test: RateSnapshot(Clock.fixed(fixedUtc));
double amount / num price fields. Cannot represent 0.01; corrupts
totals irreversibly. Use int minor units.amount * 100 / cents / 100. Wrong for every non-2-exponent currency.
Route through currency.minorPerMajor.Money across currencies, or storing a currency per line item when the
whole aggregate is single-currency. Convert at the FX boundary; keep currency
at the aggregate level.allocate() a known integer total instead.allocate().total on the entity. Derive it.DateTime.now(), or a hand-rolled ClockService/SystemClock/FakeClock,
inside the pure core. Untestable / non-composable time. Inject
package:clock's Clock.Decimal(someDouble) or int.parse on raw localized input. Binary error /
throws on Eastern digits. Parse Decimal from a String; normalize first.int minor units + a Currency; no double/num.currency.minorPerMajor; no literal 100.allocate(); conservation asserted and tested with
the verified vectors.allocate().id; relationships are id links.ints; converted only at the edge.Clock; no DateTime.now() in core.decimal and clock; no Flutter/intl/dart:io.scripts/check-money-violations.sh and scripts/verify-core.sh pass.project-structure-and-packages for where this pure core lives (lib/core/,
the sanctioned foundation layer) within the feature-first app layout.service-boundary-and-native for injecting this Clock into Riverpod
code via clockProvider (the same package:clock seam, provider-wired).error-handling-typed-results for the sealed Result<T, F extends Failure>
spine that parsing and FX return instead of throwing.i18n-rtl-l10n for ASCII digit/separator normalization and currency
formatting at the presentation edge (kept out of this pure core).dart3-idioms-and-coding-standards for immutable value types, sealed types,
and total non-throwing domain functions.persistence-drift for storing minor units + ISO code (never a REAL) and
mapping rows to these value objects.testing-strategy for the clock-injected, table-driven unit tests these
pure functions demand.package:decimal — https://pub.dev/packages/decimalpackage:clock — https://pub.dev/packages/clockfake_async — https://pub.dev/packages/fake_asyncexamples/allocate.dart (opens in a new tab)examples/money.dart (opens in a new tab)references/allocate-and-splitting.md (opens in a new tab)references/canonical-storage.md (opens in a new tab)references/domain-model.md (opens in a new tab)scripts/check-money-violations.sh (opens in a new tab)scripts/verify-core.sh (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub zakariaf/flutter-skills --plugin flutter40 skills in this plugin
/accessibility-as-codeEnforces accessibility as a correctness property authored into each widget — Semantics(button/label) or ExcludeSemantics on every node, a11y state read from MediaQuery not app state, never MediaQuery.withClampedTextScaling / textScaleFactor / FittedBox / TextOverflow.ellipsis to fit a label, non-color redundant channels (icon+label+shape+text) for every state, contrast against composited backgrounds (4.5:1 body / 3:1 large), 44px single-tap targets, OrdinalSortKey traversal, and honoring boldText / reduce-motion. Use when adding a GestureDetector/InkWell or any tap target, adding an Icon or Image, reaching for withClampedTextScaling/FittedBox/ellipsis/textScaleFactor to make text fit, encoding state via color, sizing type, ordering focus traversal, or reviewing any View for screen-reader/switch/low-vision support./adaptive-layoutEnforces adapting layout by available CONSTRAINTS/size, never device or platform checks — LayoutBuilder + MediaQuery.sizeOf/paddingOf/viewInsetsOf (not .of) for narrow rebuilds, Material 3 window size classes (compact <600, medium 600-840, expanded 840-1200, large >1200) as the breakpoint vocabulary, navigation affordance chosen by width (NavigationBar → NavigationRail → NavigationDrawer), list-detail single-pane-vs-two-pane, readable max-width via ConstrainedBox, Flexible/Expanded/FractionallySizedBox over fixed widths, SafeArea + display cutouts + keyboard insets, never lock orientation, foldable/hinge awareness via MediaQuery.displayFeatures, and golden-matrix verification across sizes. Use when building responsive or adaptive UI, tablet/desktop/foldable support, master-detail or two-pane screens, a NavigationRail-vs-BottomNav shell, breakpoints, LayoutBuilder, MediaQuery sizing, SafeArea/cutouts, or fixing overflow at large widths./ads-and-iap-monetizationEnforces opt-in, rewarded-first monetization over the service seam — a rewarded view grants exactly one benefit and only on a genuine reward outcome (a sealed Rewarded/Dismissed/NoFill), earn loops capped per day against an injected Clock, the earn control preloaded and hidden unless an ad is loaded so a fresh account never dead-ends on "no ads available" (a Guideline 2.1 risk), interstitials only at a natural break under a count-and-elapsed cap owned by the service so callers stay dumb, no banner on the primary work surface, one non-consumable unlock plus Restore re-checked each launch and committed through the single write path before the UI reacts, one derived isEntitled provider as the only gate, and the entitlement restored BEFORE the ad SDK initializes so a paying user never starts it, resolves consent, or sees a tracking prompt. Use when adding ads, wiring a rewarded earn loop, placing an interstitial, building a paywall, gating an entitlement, or setting up ad units./app-startup-and-bootstrapEnforces a fixed main() cold-launch order — crash-log sink + FlutterError.onError + PlatformDispatcher.onError installed BEFORE any code that can throw, settings/theme read before runApp so the first frame paints correct, real infra constructed in a composition-root bootstrap() and injected via ProviderScope overrideWithValue over throwing placeholder providers, non-blocking warm-up deferred to addPostFrameCallback, exactly two error handlers with NO runZonedGuarded, ProviderException unwrapped before logging, and a WidgetsBindingObserver that flushes durable state on background/resume. Use when editing lib/main.dart, main_<flavor>.dart, bootstrap.dart or app.dart, reordering anything in main(), adding a splash/onboarding/permission gate, restoring theme before first paint, wiring a DB or service into ProviderScope, handling app-lifecycle background/resume flushes, or chasing cold-start latency, ANRs, or first-frame jank./async-safetyEnforces no-silent-failure async discipline in Flutter/Dart — the arrow-callback Future-drop hole no lint catches (`onTap: () => vm.save(x)`), void-returning event handlers, a mounted/ref.mounted guard after EVERY await before touching BuildContext, capturing Navigator/ScaffoldMessenger before the gap, honest `unawaited()` that always ends in catchError, no empty/bare catches, `rethrow` over `throw e`, and disposing every StreamSubscription/StreamController/Timer/sink. Use when writing or reviewing async/await, wiring onTap/onPressed/onSubmitted or any VoidCallback, touching BuildContext after an await, writing initState/dispose/addPostFrameCallback, adding a Timer or Future.delayed, writing a try/catch, or seeing use_build_context_synchronously, cancel_subscriptions, close_sinks, unawaited_futures, or discarded_futures./ci-pipeline-and-gatesEnforces a lean GitHub Actions Flutter CI where every gate maps to one named release-blocking contract — pinned runner + subosito/flutter-action@v2 toolchain, dart format --set-exit-if-changed, flutter analyze --fatal-infos, build_runner and drift schema freshness (git diff --exit-code), flutter test --test-randomize-ordering-seed random, static import/banned-string greps that catch what runtime can't, coverage-as-report-never-a-gate with the upward-lie fixed, verify-never-bless goldens (no --update-goldens in CI), and an honest statement of what CI cannot prove (audio, real fonts, on-device behaviour). Use when editing .github/workflows/*.yml, adding or removing a job or step, wiring a codegen/schema/format/analyze/coverage gate, writing a grep-based policy test or gate script under test/policy or tool/, pinning action versions, or claiming CI proves something it can't.Other plugins' skills for the same job