countman 0.3.0
countman: ^0.3.0 copied to clipboard
High-performance counter, countdown & stopwatch animations for Flutter. One shared vsync ticker drives every instance — no per-widget timers, built for high concurrency.
Changelog #
0.3.0 #
Migration guide: MIGRATION.md.
Breaking #
CountmanPlugin.tickreturns anint(microseconds until the plugin needs the next frame) instead of abool:CountmanPlugin.idle(-1, nothing to do),CountmanPlugin.nextFrame(0) or a positive wake-up delay.CountmanPluginalso gained a requiredonDetach(). Migrate: change the return type, return one of those values and add anonDetach()(an empty body is fine).TaskQueuePlugin.beginFrameandstepreturnvoid, andsteplost itsshouldProcessparameter. The wake-up time comes from the new overridablenextWake(task)(defaultnextFrame). Migrate: drop the return values and the extra parameter.ClockPluginsubclass hooks work in integer microseconds:valueOfbecamevalueMicrosOf,thresholdCrossedbecamethresholdWake(value, thresholdMicros), and two hooks are new and required:boundaryWake(task, value, intervalMicros)andcompletionWake(task, value)(displayMicrosOfis optional). The constructor accepts aclock. Migrate: see the table in MIGRATION.md.CountdownOptions.durationis optional andCountdownOptions.deadlineis new; provide exactly one. Migrate: keepduration:for relative countdowns, usedeadline: DateTime(...)for absolute ones.- Clock semantics: a
Durationcountdown (duration, or a widget'sto: Duration(...)) and every stopwatch run on the monotonic clock, so changing the system time no longer affects them; adeadline(or a widget'stoasDateTime/int/String) runs on the wall clock. After pause/resume orreset()a task continues on the monotonic clock.remainingUntil/resolveDeadlinetake an optionalclock. Migrate: if you relied on aDurationcountdown following system-time changes, pass an absolutedeadlineinstead. - The plugin registry is keyed by instance, not by name. Registering a
different instance with an existing name asserts in debug builds (release
builds still register it); it used to be ignored silently.
Countman.unuse(plugin, {bool dispose = true}). Migrate: reuse one instance per group, or give every instance a uniquename. - Changing the resolved plugin (or
precise) no longer restarts running tasks; they migrate to the new plugin keeping remaining / elapsed time, laps, pause state and the displayed value. Migrate: callcontroller.restart()if you relied on the restart. CounterBuilder.builderis nullable (the constructor parameter is still required) because of the newCounterBuilder.listenable. Migrate: only code that reads thebuilderfield of aCounterBuilderis affected.- Default styles are resolved as widget
style> provider*Style(deprecated) >CountmanTheme> built-in default. Migrate: move provider-level*Stylearguments intoCountmanTheme.
Added #
- Clock abstraction:
CountmanClock(wallMicros,monotonicMicros),SystemClock(default; once the app returns to the foreground it adds back the time the monotonic clock stood still during device deep sleep),OffsetClockfor server-time correction andManualCountmanClock(advance,jumpWall,suspend) for tests.CountmanClock.systemcan be replaced globally;Countdown/Elapsedtake aclockargument. CountdownOptions.total(progress denominator, e.g. a whole auction window) androundingwithCountdownRounding { floor, ceil }(ceilshows 10 for 9.3 s). Completion and thresholds still use the real remaining time.total/roundingare forwarded byCountdownBuilder,TextCountdown,RingCountdown,BarCountdown,DialCountdownandCardCountdown.CountdownFormat.template(pattern): tokens{d} {H} {HH} {TH} {m} {mm} {TM} {s} {ss} {S} {SSS}, parsed once, e.g.'{d}天 {HH}:{mm}:{ss}'.- Elapsed:
ElapsedOptions.since(wall-clock start) /initial(monotonic offset; mutually exclusive),limit+onComplete,ElapsedHandle.updateLimit, laps throughElapsedHandle.lap()/lapsandElapsedController.lap()/laps.ElapsedBuilder/TextElapsedtakesince,initial,limitandonComplete. - Controllers expose
runState(CountmanRunState: idle / running / paused / completed) andrunStateListenable, plusrestart()anddispose()(CounterValueController,CountdownController,ElapsedController;AnimatedCounterControllergetsrunState/runStateListenable).CountmanRunStateNotifieris the mixin behind it. CountmanTheme(aThemeExtension) carries the default style of every display widget; every*Stylehas a staticlerp;CountmanTheme.maybeOf/of.AnimatedCounter/AnimatedCounterBuilder:plugin(explicit > nearestCounterProvider>defaultCounter, so the provider'sonGroupReady/onAllCompleteapply) andanimateOnce.CounterFormat.format(value, {minValue, maxValue})returns the string anAnimatedCountershows at rest.CounterBuilder.listenable/CountdownBuilder.listenableconstructors push values through aValueListenableinstead of rebuilding every tick;RingPainter/BarPaintertake an optionalprogressListenable.CardCountdown.semanticsLabel(default'Countdown').RingStyleandBarStyleare exported themselves, not only their aliases.
Changed #
- The scheduler sleeps between updates: when no plugin needs a frame within about 20 ms it arms one global timer and requests a frame when it fires. A once-per-second countdown no longer produces a frame per vsync.
- Clock tasks update when their own value crosses a multiple of
interval(per-task buckets, not a plugin-wide phase);onCompletefires on the frame containing the deadline. CountdownBuilderandCardCountdownreadCountdownProvider.plugin, soonAllCompletealso fires for cards.CounterBuilder,CountdownBuilder,ElapsedBuilderandCardCountdownresolve the plugin and the reduced-motion setting the same way.AnimatedCounteris split by responsibility (DigitRollEngine, oneresolveDigitMotionshared by the painter and widget-tree paths, part files for config / timeline / scope / measure / tint / controller binding / state). Behaviour is unchanged.AnimatedCounterhonoursMediaQuery.disableAnimations; the direction tint is driven by the shared ticker and no longer rebuilds during the fade.RingCounter/RingCountdown/BarCounter/BarCountdownkeep one painter alive and repaint through aListenable; semantics update only when the integer percentage changes.- The three controllers moved to
lib/src/controllers/(imports throughpackage:countman/countman.dartare unchanged). - A runState written during build is published at the end of the frame, so
listeners may call
setStatesafely. animateOncewithout a stable id or without a provider no longer asserts: it logs one debug warning and plays the animation every time.- Dial 刻度环与翻牌卡面复用全局 LRU 位图,按 RGBA 字节估算分别限制在
32 MiB / 8 MiB;生成失败或单张超预算时回退矢量,淡化及自定义翻牌画笔
保持矢量路径。新增
DialCountdown.clearTickImageCache()与FlipCardPainter.clearFaceImageCache():释放共享位图,下次绘制按需重建, 不清理文字缓存,也不主动触发重绘。 - 新增
Countman.fps全局显示上限与插件 / Options / 组件实例覆盖,默认 null 保持原行为;完成与阈值不受限帧影响。Counter 限帧读单调钟,CardCountdown 改由私有共享 Counter 进度任务驱动,fps 真正降低出帧;静音优先。 FlipCardPainter.controller放宽为Animation<double>,继续接受 AnimationController; 卡片无独立 Flutter Ticker,保持 calendar 往返、单程过渡、减弱动画与像素输出。- 组件默认随 TickerMode 不可见休眠:不投递 onUpdate/onTick,完成与阈值仍按真实
时间触发;恢复直接显示当前值,Counter 采用真实时间推进的方案 A。新增
Countman.muteWhenHidden开关;CardCountdown 隐藏/恢复时落定翻牌。 CardCountdownshares glyph caches across equal styles and reuses painter glyph references and rotation matrices, reducing memory and paint overhead without API or visual changes. Clarified calendar's two-segment duration.
Fixed #
slideScaleon the painter path no longer scales the slide offset with the canvas, matching the widget-tree path.CountmanThemecard styles apply when there is noCardCountdownProvider.- 翻牌淡化保留背景与数字分别合成的透明度;刻度发光及整卡旋转的 大字、文字阴影通过位图边距保留,calendar 半卡仍裁到原卡面。
- 修复 fps 的 vsync 对齐漂移(60Hz 下 precise Countdown 30fps 降为 20fps) 及 Counter 空轮询帧:固定网格推进,按屏幕刷新率以半个 vsync 容差对齐唤醒, 达到屏幕刷新率时不再节流;显示桶、完成与阈值不提前。
Deprecated #
- The 38 flat
AnimatedCounter/AnimatedCounterBuilderparameters that duplicateformat/timeline/style(for examplefractionDigits,duration,textStyle). Behaviour and precedence are unchanged; move them intoCounterFormat/CounterTimeline/AnimatedCounterStyle. - Provider
*Styleparameters onCounterProvider,CountdownProvider,ElapsedProviderandCountmanProvider: useCountmanTheme. CountdownProvider.animateOnce: countdowns have no entrance animation, so the flag has no effect.
0.2.5 #
Fixed #
- Controllers (
CounterValueController,CountdownController,ElapsedController,AnimatedCounterController) stay bound when a widget is re-keyed or a controller is handed from one widget to another in the same frame; the old widget's dispose no longer detaches the new binding. - Swapping only the
controllerno longer restarts the task: countdowns keep their remaining time and pause state, stopwatches keep their elapsed time, counters don't replay, and no lifecycle callbacks fire. CounterValueController.update()after the animation finished,CountdownController.reset()after completion andElapsedController.reset()aftercancel()now relaunch the task instead of doing nothing.CounterBuildercalls the currentonComplete/onReady/onStart/onCancelinstead of the ones captured at mount.- A throwing task callback no longer starves the other tasks of the same group
or stops the shared ticker; a task whose
onCompletethrows is still removed and the group still drains.Countman.destroy(), plugin disposal andStartSchedulerbatches isolate callback exceptions too (reported throughFlutterError.reportError), and cancelling an owner inside a running batch skips its pending start. - Countdown completion and thresholds are checked every frame (display updates
are still throttled by
interval):onCompletefires on the deadline frame instead of up to one interval late, andDuration.zero/ past deadlines complete on the first frame. Each clock group reads the clock once per frame. ElapsedHandle.pause/resume/resetare no-ops aftercancel().RingCounter/BarCounterforward theirValueKeyto animate-once, so they no longer assert underCounterProvider(animateOnce: true).- Ring painter: progress scales the cap-adjusted sweep, so a full ring moves from the first tick instead of freezing for the first ~3.5 % (about two minutes of a one-hour countdown); the thumb no longer paints outside the widget bounds.
- Ring and bar painters resolve directional gradients (
AlignmentDirectional) with the ambientDirectionalityinstead of throwing every frame. AnimatedCounter/AnimatedCounterBuilder:- retargeting mid-roll continues from the on-screen value (including each column's fractional progress) instead of jumping to the previous target;
fastmode shows a static non-zeroinitialValue, collapses old leading digits after completion, and the builder path's group separators follow the same visibility rule;jumpTolands immediately even when it targets the running animation's value, skippingstartDelay, stagger and bounce;resume()only resumes a paused animation (no replay or duplicateonAnimationEndafter completion);restart()duringstartDelaykeeps the new target; commands issued fromonAnimationStartare no longer overwritten by the outer transition;- changing only
minValue/maxValuere-renders the digits; increasingColor/decreasingColornow tint the digits on both paths (quantized palette, no per-frame text re-layout);- horizontal
slide(flipDirection: left/right) moves along the x-axis on the painter path as well; - compact-notation semantics read the displayed value (
1.2M, not12); - status listeners receive
forward/reverse/completed/dismissed.
CardCountdown: hour cells expand as needed (100 h and more no longer squeeze12into one cell); togglingshowHoursuses the live remaining time; the screen-reader value updates every tick; identical consecutive ticks no longer restart the flip; flip and fade keep the card and text colors' own alpha; glyph caches drop stale styles and the shared cache is bounded.DialCountdown: the inner ring draws at most four arcs regardless of the total duration (a 30-day countdown used to draw tens of thousands per paint); repaired garbled characters in the API docs.OdometerCounter: non-finitefrom/toare treated as 0 instead of throwing;onCompletereports the clamped displayed value.fractionDigits/compactFractionDigitsabove 20 are rejected by an assert (they used to throw aRangeErrorwhile building semantics).
Added #
CardCountdown.showDays/dayLabelfor a leading days unit.RingCounter.animateOnce/BarCounter.animateOnce.textDirectiononRingPainter/BarPainter(andringPainterFrom/barPainterFrom) to resolve directional gradients.ElapsedHandle.isDone.
Changed #
- Minimum SDK is Flutter 3.35 / Dart 3.9. The package already needed it:
@internalis imported frompackage:flutter/foundation.dart, which only exports it since Flutter 3.35. BarStyle.width/heightare literal layout sizes; a vertical bar without explicit sizes now defaults to 8×200 (it used to be 200×8).- The published package no longer ships the stray
flutter_01.log; added a.pubignore.
Deprecated #
thousandSeparatorWidget/decimalSeparatorWidgetonAnimatedCounter: the painter path never rendered them. UseAnimatedCounterBuilder.
0.2.4 #
Added #
- Add
CounterTimelinefor immutable animation configuration onAnimatedCounterandAnimatedCounterBuilderviatimeline; non-null fields override loose parameters, null fields fall back, and value-equal configurations preserve the running animation and painter. - Add
CounterFormatfor shared immutable formatting configuration onAnimatedCounterandAnimatedCounterBuilder; non-null object fields override loose parameters, while null fields fall back to them.
0.2.3 #
Fixed #
- Counter painter: hide leading zeroes only in the integer part (keep the
units digit, fraction digits and decimal point, e.g.
0.05); share right-anchored grouping boundaries between painter and widget paths. - Counter painter: rebuild on any config change (separators, numerals, padding, alignment, builder) and always repaint a replaced painter; draw digits with the full text style, system text scale and the original colour alpha; cache column layout and release Dial tick labels.
AnimatedCounterController.jumpTocancels the running roll and bounce;pause/stopalso coverstartDelay, batched starts and bounce.speedMultiplierscales stagger once;repeat(reverse: true)loops back and forth until stopped;reverse()swaps fast-mode endpoints too.- Reduce-motion now applies to the
AnimatedCounterroll and card updates. - Replace always-true render assertions with captured-exception checks and guarantee shared fixture cleanup even when an assertion fails.
- Align
AnimatedCounterStyleequality with the runtime-type contract used by the other styles.
Changed #
- Share number clamping, compact formatting, rounding and digit extraction across both animated counter renderers; share painter column spacing with full-width measurement.
- Reuse constant default abbreviations and sort custom thresholds once per configuration change, including in-place map changes on widget or controller updates.
- Update examples to omit inert odometer and bounce arguments.
Deprecated #
- Mark inert
OdometerCounterparameters (plugin,controller,slideCurve,onUpdate,onReady,onCancel) and style fields (letterWidth,verticalOffset,fadeEnabled) deprecated without removing them. - Mark
bounceElasticitydeprecated on both animated counters and the odometer; usebounceOvershootinstead. All existing parameters and defaults remain.
0.2.2 #
Docs only — no code changes.
Fixed #
- README (EN/ZH) demo link/badge now points to the package-specific demo
path (
/countman/) instead of the shared monorepo landing page.
0.2.1 #
Docs only — no code changes.
Fixed #
- README screenshots and cross-links (EN/ZH) now use absolute URLs so they
render on pub.dev. Relative paths broke because the package lives in a
monorepo subdirectory (
countman/), which pub.dev resolves against the repo root.
0.2.0 #
Counter transition redesign + internal consolidation.
Changed (breaking) #
AnimatedCounter/AnimatedCounterBuilder:transitionType(CounterTransitionType) →transition(CounterTransition) — a composable look built from aCounterMotion(none/slide/rotate/flip) plusscale/fade/blurmodifiers, with presets.slide(default),.slideScale,.slideBlur,.rotate,.flip,.flipFade.- Removed the
AnimatedCounter.usd/.cny/.inrcurrency factory constructors — composeprefix+groupingPattern([3]/[4]/[3, 2]) directly instead. OdometerCounteris now a thinAnimatedCounterdelegate (aStatelessWidgetreusing the shared painter).bounceElasticityis retained for source compatibility but no longer has an effect — bounce is driven bybounceOvershoot.
Added #
- Leading-zero-at-rest fade-in: hidden leading zeros fade in/out by the live
cumulative place value instead of popping (e.g.
1000 → 7collapses to7). - Per-column bounce wave that follows a staggered roll.
Internal #
- Odometer trajectory + end-of-roll ghost-prevention math extracted into one
shared
resolveDigitPhaseused by both the painter and widget-tree paths; the paint/build hot paths stay allocation-free via a reusedDigitPhase. - The default (
slide/none) paint path skips a redundant canvas save/restore pair. - Default-plugin registration unified on first task (
LazyDefault+enqueueself-register), with a central reset onCountman.destroy(). CountmanTask.reanchor()replaces ad-hocstartedtoggling for retarget / resume / reset.
0.1.0 #
Initial release.
A high-performance counter / countdown / elapsed animation library for Flutter.
One shared scheduleFrameCallback ticker drives every instance — adding the
hundredth counter costs the same as the first.
Engines #
Counter(value interpolation),Countdown(wall-clock deadline, interval- gated),Elapsed(open-ended stopwatch). Top-levelcounter()/countdown()/elapsed(), shareddefaultCounter/defaultCountdown/defaultElapsedand precise (interval: 0)defaultCountdownMs/defaultElapsedMs.
Widgets #
- Counter:
TextCounter,RingCounter,BarCounter,OdometerCounter,AnimatedCounter(+.usd/.cny/.inr),AnimatedCounterBuilder,CounterBuilder. - Countdown:
TextCountdown,RingCountdown,BarCountdown,DialCountdown,CardCountdown,CountdownBuilder. - Elapsed:
TextElapsed,ElapsedBuilder.
Features #
- Per-widget
*Styleobjects (colors, gradients,decoration+padding, ringsweepAnglegauge /startAngle/showTrack/ leading thumb dot, barvertical/showTrack);painterBuilderescape hatch on ring/bar/dial. - Imperative controllers:
CounterValueController,AnimatedCounterController,CountdownController,ElapsedController(pause / resume / reset / status). - Providers:
CounterProvider,CountdownProvider,ElapsedProvider, aggregateCountmanProvider, andCardCountdownProvider(shared glyph cache). precise: truesub-second updates;onTick(TimeParts);threshold+onThreshold; full lifecycle callbacks;animateOnce(play once per key).- Formatters
CountdownFormat.{hms, ms, msTenths, msMillis, dhms, dhm, auto}. StartScheduler(batch grid startup across frames); injectablecountdownClockfor testing / server-time alignment.
Zero third-party runtime dependencies.