The bloc ecosystem vs Juice
1. Family snapshot
Versions read (felangel/bloc master pubspecs, 2026-09-16): bloc 9.2.1, flutter_bloc 9.1.1, bloc_concurrency 0.3.0, hydrated_bloc 11.0.0, replay_bloc 0.3.0, bloc_test 10.0.0, bloc_lint 0.4.2, bloc_tools 0.1.0-dev.24. Sources read: raw.githubusercontent.com/felangel/bloc/master/packages/<pkg>/lib/src/ — bloc.dart, emitter.dart, bloc_base.dart, bloc_observer.dart, the three bloc_concurrency transformers, hydrated_bloc.dart, hydrated_storage.dart, replay_bloc.dart, change_stack.dart, bloc_test.dart, mock_bloc.dart, when_listen.dart, bloc_builder/listener/selector/provider.dart, bloc_lint linter.dart + rules/. Docs: https://bloclibrary.dev/bloc-concepts/, /flutter-bloc-concepts/, /architecture/, /lint/, /lint-rules/*; pub.dev pages for each package and for bloc_devtools_extension; https://github.com/felangel/bloc/issues/2748.
Philosophy. Bloc is a small, stream-shaped core: BlocBase holds state behind a broadcast StreamController; Bloc pipes add(event) through a per-handler EventTransformer into on<E> handlers that receive an Emitter; one global Bloc.observer sees create/event/change/transition/error/done/close. Felix’s reason to prefer Bloc over Cubit is traceability: “One of the biggest advantages of using Bloc is knowing the sequence of state changes as well as exactly what triggered those changes.” Everything else (hydrated, replay, concurrency, test, lint) is a mixin, a transformer or a tool on those three seams (emit, observer, transformer). Layering: data → repository → bloc → presentation; “sibling dependencies between two entities in the same architectural layer should be avoided at all costs” — bloc-to-bloc goes through BlocListener in the UI or a shared reactive repository.
2. Mechanism catalog
Event handlers + event transformers (on<E>, Bloc.transformer)
- What it does: one handler per event type; a transformer decides how same-handler events interleave;
Bloc.transformersets the global default. - How it works:
add()asserts a handler exists (debug), callsonEvent, adds to a broadcast_eventController.on<E>subscribes(transformer ?? Bloc.transformer)(events.where((e) => e is E).cast<E>(), mapper). The mapper builds a fresh_Emitter(onEmit)per event plus a sync broadcast controller whoseonCancel: emitter.cancel, runshandler(event, emitter)withfinally { emitter.complete(); controller.close() }, and returnscontroller.stream— a handler’s lifetime is modelled as a stream that transformers flatten, queue, drop or switch. Default isevents.map(mapper).transform(_FlatMapStreamTransformer())= concurrent. Matching ise is E, so a handler on a base event type receives the whole hierarchy and its transformer serializes across subtypes. - Juice today:
has-under-another-name(UseCaseBuilder.concurrency,core/event_dispatcher.dart).partial: Juice matches by exactruntimeType, so there is no cross-type lane — ROADMAP records juice_sync’s Retry↔Discard “documented, deferred cross-type window” for this reason. - Gap value: Med — any bloc with several mutation events on one collection needs one FIFO across types.
- Adoption sketch: a
laneonUseCaseBuilder(concurrency: sequential, lane: 'queue'): the dispatcher keys_tails/_runningby lane when given. Core, cost S. Not base-type handlers. - Doctrine fit: needs a knob (
lane), but it widens the key of the existingconcurrencyknob rather than adding a purpose; ROADMAP already names the need (“a bloc-owned FIFO closes it; no consumer yet”).
bloc_concurrency: sequential / droppable / restartable
- What it does: the three non-default interleavings as transformers.
- How it works:
sequential=events.asyncExpand(mapper).droppable= a hand-written_ExhaustMapStreamTransformerthat discards events whilemappedSubscription != nulland resets ononDone.restartable=events.switchMap(mapper)fromstream_transform; the fence is indirect and elegant:switchMapcancels its subscription to the previous handler’s stream → the sync controller’sonCancelrunsemitter.cancel()→_isCanceled = true, allforEach/onEachsubscriptions in_disposablesare cancelled, the completer completes, and every lateremit()from the superseded handler is a no-op (if (!_isCanceled) _emit(state)). Side effects are not undone; docs warn it is “only for asynchronous APIs”. - Juice today:
partial—concurrent/sequential/droppableshipped in 1.5.0 (_sequentialchains per-type_tails,_droppableuses_running);restartableis a comment inevent_concurrency.dartand ROADMAP tee-up item 3, whose epoch-fence design matches bloc’s semantics exactly. - Gap value: Med (typeahead, scrubbing, latest-search-wins).
- Adoption sketch: per-type epoch in
EventDispatcher; theUseCaseContextemits no-op whenepoch != current, loggingstate_emission_skippedwith reasonsuperseded; the superseded event isCancellableEvent.cancel()led soisCancelleddoubles as bloc’semit.isDone. Core, cost S–M. - Doctrine fit: fits (fourth value of the one knob). Gate stands: a real consumer.
Emitter.forEach / Emitter.onEach
- What it does: binds a stream to state for the life of one handler, cancellation tied to handler and bloc.
- How it works:
onEachsubscribes, pushessubscription.cancelinto_disposables, and returnsFuture.any([emitter.future, completer.future]).whenComplete(cancel)— the binding ends when the stream completes or the emitter is cancelled (restartable/close).forEachisonEachwithonData: (d) => call(onData(d)).complete()asserts_disposables.isEmpty(“An event handler completed but left pending subscriptions behind… unawaited emit.forEach”);call()asserts!_isCompleted(“emit was called after an event handler completed normally… unawaited future”).close()cancels every live emitter and awaits their futures before closing state. - Juice today:
lacks. Every streaming package hand-rolls it on the bloc:juice_location/lib/src/location_bloc.dart:82,juice_llm/lib/src/llm_bloc.dart:290,juice_realtime/lib/src/realtime_bloc.dart:154,juice_connectivity:72,juice_lifecycle:55(_sub = x.listen(...), cancel inclose());StatefulUseCaseBuilderis the only helper. - Gap value: High for package authors (five packages repeat the pattern; the leak surface is per-package), Med for apps.
- Adoption sketch:
BlocUseCase.bindStream<T>(stream, {required BlocState Function(T) onData, groupsToRebuild, onError}), returning a future that completes on stream done,CancellableEventcancel, or bloc close (the dispatcher’sclose()cancels registered bindings); emits go throughemitUpdateso groups and telemetry apply; the executor asserts no binding outlivesexecute()unless the builder isStatefulUseCaseBuilder(long-lived subscriptions are its stated purpose). Core, cost M. Migratejuice_locationfirst. - Doctrine fit: fits (helper, no knob; makes gotcha 8 partly automatic).
Bloc-wide == dedup and emit-after-close
- How it works:
BlocBase.emitthrowsStateError('Cannot emit new states after calling close');if (state == _state && _emitted) return;is always-on (first emit always passes);onChangeruns before the store. - Juice today:
has-under-another-name—StatusEmitter._emitthrows on closed; dedup is per-callskipIfSame, deliberately not bloc-wide (AGENTS §4c: a blanket mode “would swallow intentional re-emits”). Not a gap. Gap value Low.
BlocObserver (+ MultiBlocObserver, Transition/Change)
- What it does: one global object receives
onCreate,onEvent,onChange(Change{currentState,nextState}),onTransition(Transition{currentState,event,nextState}),onError,onDone(event[,error])(9.1.0),onClose; 9.2.0 addsMultiBlocObserverfan-out. - How it works:
BlocBasecapturesBloc.observerat construction (final _blocObserver = Bloc.observer), so an observer installed later misses existing blocs; hooks are@protected @mustCallSuperinstance methods delegating to it.onTransitionfires only fromon<E>’sonEmit; no ids, no timing —onDonecannot be paired with its transitions when same-type events overlap. - Juice today:
has-under-another-name— theJuiceLoggerseam + typedcontext['type']taxonomy andDevtoolsJuiceLoggeras the tee;StreamStatus(state, oldState, event)is a Transition with status attached.partial: no typedonCreate; consumers parse string-typed maps (the DevTools extension re-derives a model intelemetry_model.dart). - Gap value: Low–Med (tooling authors).
- Adoption sketch: promote the extension’s model into
juice_observabilityassealed class JuiceTelemetry+JuiceTelemetry.parse(context)— typed consumption on the existing seam. Cost S. - Doctrine fit: fits only as a decoder on the logger seam; a separate observer object would be a second knob for the same purpose — reject that form.
Cubit
- How it works:
abstract class Cubit<State> extends BlocBase<State>— three lines; methods callemit. The observer seesChanges with no event;prefer_cubit/prefer_bloc/prefer_void_public_cubit_methodspolice the style. - Juice today:
has-under-another-namefor the ceremony problem only (InlineUseCaseBuilderkeeps the event, givesctx.emit.update(...)). - Gap value: Low. Doctrine fit: conflicts (one use case per event; Felix’s traceability argument is Juice’s argument). Reject.
hydrated_bloc
- What it does: persist every state change; restore at construction.
- How it works:
HydratedMixin.hydrate()runs in the constructor;__storage.read(storageToken)is synchronous (the Hive CE box is already in memory),_state = fromJson(json) ?? super.state, and thestategetter is overridden to_state ?? super.state.onChangewritestoJson(nextState)after every emit._traverseWritevalidates the tree: atomics pass (non-finitenum→NIL),List/Maprecurse with a_seenstack for cycle detection (HydratedCyclicError), custom objects get.toJson()called dynamically, anything else throwsHydratedUnsupportedError— a non-serializable field fails at first write, not at restore. Key =storagePrefix(runtimeType; override for minification) +id(multi-instance).Storage(readsync,write/delete/clear/closeasync) isHydratedStorageover one Hive CE boxhydrated_boxbehind asynchronizedLock,HydratedStorageDirectory.websentinel, optional AES cipher, one-shot migration of the legacy.hydrated_bloc.json. 10.1.0 addedonHydrationError → HydrationErrorBehavior.overwrite|retain(default overwrite: a corrupt read is clobbered by the next write). No schema versioning or migration — apps branch insidefromJson. - Juice today:
partial. The substrate exists (juice_storage2.2.0, awaitableinitialize()), persistence is per-package behind seams (ThemePersistence.load/save, notes_appauto_save_use_case), but there is no generic “restore this bloc’s state, save on emit” capability and noBlocStatein the family hastoJson(grep*_state.dart: 0). - Gap value: High for app authors (settings, drafts, offline-first) — the most-used bloc add-on; every Juice app re-derives it.
- Adoption sketch: a
StatePersistence<TState>seam in core (Future<Persisted<TState>?> load(),Future<void> save(TState, {required int version})), optional on theJuiceBlocconstructor; a built-inHydrateEvent(droppable, viainitialEventBuilder) thatemitWaitings thenemitUpdates the restored state on ahydrategroup — the awaitable storage becomes an honestWaitingStatusinstead of bloc’s sync trick; saves queue on a built-insequentialPersistStateEventtriggered fromStatusEmitter.emitUpdateonly.juice_storageshipsStorageStatePersistence(Hive) +InMemoryStatePersistence(fake). Fail loud where bloc is silent:version+ requiredmigrate(from, json); unknown version →emitFailure, never overwrite. Cost M. - Doctrine fit: fits (seam + default + fake; events → use cases; groups). Flagged for veto: when no seam is passed the built-in events are simply not registered — absence of a feature, not a fallback.
replay_bloc
- What it does: undo/redo with bounded history and a replay filter.
- How it works:
ReplayBlocMixinoverridesemit: beforesuper.emit(state)it pushes_Change(old, new, redo, undo)onto_ChangeStack— twoListQueues (_history,_redos);addclears redos and trims tolimit.undo()moves the last change to redos and runs its closure, which synthesizes a private_Undoevent, callsonEvent+onTransition(the observer sees undo as a real transition) andsuper.emit(old);redomirrors.shouldReplay(state)is consulted at replay time; non-replayable entries are skipped recursively (canUndo=_history.any(shouldReplay)).ReplayEventis the required event base so_Undo/_Redotype-check. - Juice today:
lacks(grepundo|redoinpackages/juice/lib: 0). - Gap value: Med — editors (notes_app editor bloc is the in-repo candidate).
- Adoption sketch: mirror
RetryableUseCaseBuilder’s emit interception:UndoableUseCaseBuilderwraps a builder, records(oldState, newState, groups)on eachemitUpdateinto aChangeStack<TState>held on the bloc (behavior on the bloc, not in state — gotcha 5), and registers built-inUndoEvent/RedoEventuse cases (sequential) that re-emit with the recorded groups plus ahistorygroup forcanUndo/canRedowidgets.limitandshouldReplayas constructor args. Core, cost M. - Doctrine fit: fits (decorator builder, events, groups, no state bloat). Gate: a real editor consumer.
bloc_test (blocTest, MockBloc, whenListen)
- How it works:
testBlocswapsBloc.observerfor a_TestBlocObserverthat forwards to the previous one and collectsonErrors; insiderunZonedGuarded:setUp,build(), optionalbloc.emit(seed()),stream.skip(skip).listen(states.add),await act?.call(bloc)(errors captured only iferrors:given),await wait,await Future.delayed(Duration.zero),await bloc.close(), thenexpect(states, wrapMatcher(expected)); on mismatch adiff_match_patchdiff is appended and, if'$states' == '$expected'with unequal objects, “Please ensure state instances extend Equatable, override == and hashCode”.MockBlocis a mocktailMockwithstream/closepre-stubbed;whenListenre-stubsbloc.stateas each stubbed emission passes. - Juice today:
has-under-another-name—src/testing/bloc_tester.dart(send+ 10 ms delay,sendAndWaitForResult,expectStatusSequence,expectWasWaiting/Failure,waitForEmissions).partial: noseed, no declarative act/expect, no error matcher, no diff, no mocks — and no test in the repo uses it (grepBlocTester|.tester()over*_test.dart: 0); packages test with hand-writtensettle(). - Gap value: Med (every package’s tests; consumers’ first bloc test).
- Adoption sketch:
juiceTest<TBloc,TState>(desc, build:, seed:, act:, wait:, expect: [WaitingStatus, UpdatingStatus], expectGroups:, errors:, verify:)inpackage:juice/testing.darton top ofBlocTester;seedvia the@visibleForTesting emit; errors via a testBlocErrorHandler; mismatch prints the status/group diff. Groups make the assertion richer than bloc’s (rebuild targeting becomes testable). Cost S–M. Gate: portjuice_theme’s tests. - Doctrine fit: fits; “demonstrate in full” says the framework’s own tests should use it.
bloc_lint (+ bloc_tools LSP)
- How it works: a standalone linter — not
custom_lint, not the analyzer element model.linter.dartscans/parses with_fe_analyzer_shared’sParser; rules are token-levelListeners (beginMethod,beginMetadata) —avoid_public_bloc_methodsfires whenenclosingDeclarationName.endsWith('Bloc')and the name is not allow-listed. It runs only whenpubspec.lockcontainsblocandanalysis_options.yamlhasbloc: rules:; IDE integration isbloc_tools’ language server (lsp_server_ce). Nine rules: avoid_build_context_extensions, avoid_flutter_imports, avoid_public_bloc_methods, avoid_public_fields, prefer_bloc, prefer_build_context_extensions, prefer_cubit, prefer_file_naming_conventions, prefer_void_public_cubit_methods. - Juice today:
has—juice_lint0.1.0 (custom_lint, three rules on the resolved model,TypeCheckerscoped topackage:juice).partialon coverage: ROADMAP phase 3 named use-case-per-file, no-cross-feature-deps, relay-not-listener; none built. - Gap value: Med.
- Adoption sketch: three rules, cost S each:
juice_state_read_before_await(abloc.stateread stored in a local, anawait, then that local passed toemit*in a non-sequentialbuilder — AGENTS gotcha 3),juice_feature_bloc_dependency(a feature package importing another feature bloc — ROADMAP invariant 2),juice_public_state_field(bloc’savoid_public_fields). Skipavoid_public_bloc_methods: the canonical shape has thin wrappers (void load() => send(LoadFooEvent())). - Doctrine fit: fits.
flutter_bloc widgets (BlocProvider, MultiBlocProvider, BlocBuilder, BlocListener, BlocSelector)
- How it works:
BlocProviderisprovider’sInheritedProvider— lazycreate,dispose: (_, bloc) => bloc.close()forcreateonly (never.value),_startListeningmarks dependents per emission socontext.watchworks.MultiBlocProvider extends MultiProvider.BlocListenersubscribes tobloc.stream, callslistenerwhenlistenWhen?.call(_previousState, state) ?? true, and re-subscribes when the bloc instance changes.BlocBuilderis literally aBlocListenerwithlistenWhen: buildWhen,listener: setState;BlocSelectorsetStates only whenselector(state) != _state. - Juice today:
has-under-another-name:BlocScope.register/get/lease+BlocLifecycle+FeatureScope/CleanupBarrier(ownership explicit, not tree-positional);StatelessJuiceWidget(groups)viadenyRebuild;JuiceBuilder(buildWhen: (status)),JuiceMultiBuilder;JuiceSelector/bloc.select(==) andselectWith. Side effects:JuiceWidgetState.prepareForUpdate(status)fires once per new status (the listener hook);StatelessJuiceWidgethas onlyonStateChange(a filter). NoBlocListenerwidget by doctrine; bloc-to-bloc isStateRelay/StatusRelay/EventSubscriptionwith leases. - Gap value: Low.
listenWhen(previous, current)is expressible becauseStreamStatuscarriesoldState. Adoption sketch: none; documentprepareForUpdateas the listener hook in AGENTS.
DevTools story
- How it works: there is no official bloc DevTools extension — issue #2748 “[Proposal] official bloc devtools” is open, “In progress”, assigned to felangel. Third-party
bloc_devtools_extension0.2.0 (unverified publisher) installs aBlocObserver, registers a service extension, and ships adevtools_extensionstab with History (time-travel slider, state replay), Graph, Performance. - Juice today:
has—juice_observability0.5.0DevtoolsJuiceLogger(postEventjuice:<type>, 512-char clipping) + a packaged extension (Timeline/Spans/Blocs/Problems). Ahead of the family. Worth stealing later: state diff (oldState/stateare already on the wire) and time-travel replay — which needs serializable state, i.e. depends on hydration. - Gap value: Low. Doctrine fit: already built.
3. Not worth adopting
- Cubit — eventless emit conflicts with one-use-case-per-event; Felix’s own traceability argument favors Juice’s shape.
- Bloc-wide
==dedup — Juice chose per-callskipIfSamefor the waiting→waiting reason; a blanket mode is a silent fallback. BlocProvidertree ownership —BlocScopelifecycles + leases +LeakDetectorare strictly more explicit; a provider tree would be a parallel path.BlocListenerwidget — “relays not listeners”;prepareForUpdateand relays cover it.avoid_public_bloc_methods/prefer_cubit/prefer_bloc/*_build_context_extensions— stylistic, and contradict the canonical wrapper methods andblocgetter.- Base-type event handlers (
e is E) — would undermine exact-type matching that the dispatcher andjuice_generic_eventrely on;lanegets the benefit. HydrationErrorBehavior.overwritedefault and synchronous hydrate — clobbering an unreadable persisted state is the silent fallback CLAUDE.md forbids; the sync read relies on an already-open box. Adopt hydration with versioning +WaitingStatusinstead.bloc_lint’s token-level architecture — fast, but name-suffix heuristics; the resolved-type approach is the better base.
4. Top 5 recommendations (ranked)
-
bindStream(bloc’semit.forEach) onBlocUseCase. Five shipped packages hand-rolllisten+ cancel-in-close; the framework owns the cancellation contract only by convention. A helper whose future ends on stream-done,CancellableEvent.cancel, or bloc close, emitting throughemitUpdate(groups + telemetry intact) and asserting no binding outlives a non-stateful builder, removes a leak class and makesrestartableimplementable (a superseded run’s bindings die with its epoch). Gate: migratejuice_location(location_bloc.dart:82) andjuice_llmgeneration (llm_bloc.dart:290); the bloc-side subscription fields andclose()bodies must shrink, verified underLeakDetectorin their tests. -
State hydration via a
StatePersistence<TState>seam, with versioned fail-loud migration. The most-used bloc add-on has no Juice equivalent and every app re-derives it (theme, i18n, notes autosave). Core seam +juice_storagedefault + in-memory fake; restore as an honestWaitingStatus; save only onemitUpdate,sequential; refuse unknown schema versions. Gate: one consumer that already persists (notes_app editor orjuice_theme) migrated without a second persistence path, plus a decision on whetherThemePersistence/juice_i18nseams fold into it (one knob) or stay domain-specific. -
juiceTestand dogfoodBlocTester. The tester exists and nothing uses it; bloc’s testing story is one declarative function with a diff. Addseed,expect: [status types],expectGroups,errors, a sequence diff; port one package. Gate: thejuice_themeport reads shorter than thesettle()version and asserts group targeting the current tests don’t. -
Three lint rules on the resolved model.
juice_state_read_before_await(the #1 latent bug, today only prose in AGENTS §4),juice_feature_bloc_dependency(ROADMAP invariant 2),juice_public_state_field. Gate: planted sentinels across the fivejuice_examplesapps fire; zero false positives on the 28 packages. -
restartableplus alanekey on the existing concurrency knob. Both are designed in the ROADMAP; bloc’s source confirms the semantics (fence emissions, never side effects). Keep both gated on a consumer, but notelane’s gate is nearer than it looks: juice_sync’s Retry↔Discard window is a documented defect waiting for it.
5. Things Juice does better than this family
send()returns the processing future;add()is fire-and-forget.sendAndWait/sendForResulthave no bloc equivalent — bloc_test needsFuture.delayed(Duration.zero)and await:knob to compensate.StreamStatus⊃Transition. Bloc’sTransitionexists only insideonTransition; Juice puts(state, oldState, event)plus Waiting/Failure(error,errorStackTrace)/Canceling on every emission the UI sees.- Named rebuild groups vs
buildWhen. Bloc invalidates by per-widget predicates over whole states; Juice’s groups are intent-named, cross-widget, chosen at the emit site, and testable viastatus.event?.groupsToRebuild. - Explicit ownership.
BlocLifecycle.permanent/feature/leased,BlocLease,FeatureScope,CleanupBarrier,LeakDetectorvsBlocProvider’s tree-positional lifetime and the.value-doesn’t-close footgun. - Telemetry spans.
executionId+elapsedMicrospair start/end under concurrent overlap; bloc’sonDone(9.1.0) has no id and no timing. - A shipped DevTools extension (bloc’s official one is an open issue).
- Lint on the resolved element model;
bloc_lintmatchesendsWith('Bloc')on unresolved tokens. - Cancellation and timeout as event concerns.
CancellableEvent+TimeoutSupport+emitCancel/CancelingStatus; bloc’s only cancellation isrestartable’s fence (emit.isDone). - Per-item async state (
EntityStatuses+guardEntity) and retry as a builder decorator (RetryableUseCaseBuilder+BackoffStrategy); bloc has neither primitive. - Bloc-to-bloc is first-class (
StateRelay/StatusRelay/EventSubscriptionwith leases); bloc’s doctrine is “avoid at all costs; go through the UI or a repository”. - Use-case errors are structured. Bloc
rethrows from an unawaitedhandleEvent()into the zone; Juice logsuse_case_errorwith the execution id and routes toBlocErrorHandler, while still throwing on emit-after-close.