bloc_plus 0.4.0
bloc_plus: ^0.4.0 copied to clipboard
Async helpers for Cubits, one-off effects kept out of the state, rebuild conditions and widgets that hand the bloc to callbacks, for flutter_bloc.
Changelog #
0.4.0 #
- Changed:
CancellationTokenandRestartableTaskarefinalclasses: they can no longer be extended, implemented or mocked outside the package.runLatest,guardedandCancellationToken.runtake a non-null result type only (T extends Object). Theirnullresult means that the run was discarded, which avoid, nullable ordynamicresult could not tell apart:await runLatest('save', save); emit(saved);compiled, emitted although the run was superseded, and threw afterclose(). Such a call is now a compile error.SafeEmitMixinis declaredon Cubit<S>: aBlocand a direct subclass ofBlocBasecan no longer mix it in (mixin_application_not_implemented_interface). In aBloc, the handler'semitalso callsonTransitionand does nothing in a handler that a transformer has cancelled, whilesafeEmitskipped both: underrestartable()a superseded handler emitted its stale state.RestartableTasksMixinandHasEffectsstill apply to aBloc.BlocBuilderWithBlocandBlocListenerWithBlocfollow the provided bloc right afterbloc:changes from an instance tonull, like the consumers and the selector, andbuildWhenandlistenWhenthen get their previous state from the new bloc. Before, they kept listening to the old instance while their callback got the provided one. They are now aStatelessWidgetand aSingleChildStatelessWidgetthat returnBlocBuilderandBlocListener; the constructors,const, the fields and the composition insideMultiBlocListenerstay.BlocListenerWithBlocwithout achild, outside a multi widget such asMultiBlocListener, rendersSizedBox.shrink()with every supportedflutter_bloc, asBlocEffectListenerdoes. Before, it did so only fromflutter_bloc9.1.2, and with an earlier version it failed the assertion ofBlocListener(a null check in release builds).isTaskRunning,runLatest,runLatestOutcome,cancelLatestandcancelAllLatestofRestartableTasksMixin, andguardedofSafeEmitMixin, are@protectedand@visibleForTesting, likeemit,safeEmitandemitEffect.runLatest,runLatestOutcome,guarded,CancellationToken.runandRestartableTask.runOutcomeare@useResult: the analyzer reports a result that is awaited and dropped (unused_result). Their result says whether the run counted, so the code after a dropped one ran for a superseded, cancelled or closed run as well. The bound stops that only forvoidand nullable work; with a task that returns a value, such as() => repository.save(item), it compiled without a warning.bloc_plusdepends onmeta(>=1.9.1 <2.0.0) for the annotation; Flutter itself depends onmeta, so the resolved versions do not change.BlocConsumerWithEffects.onEffectdeclares its function type inline, andBlocSelectorWithBloc.selectorShouldRebuildis aBlocCondition<T>. Both are the same function types as before.
- Fixed:
- A failure that arrives just before the run is cancelled, superseded or
its bloc closed, while the caller has not resumed yet, is dropped like a
value:
runOutcomeandrunLatestOutcomecomplete with a cancelled outcome, andrunLatestandCancellationToken.runwithnull. Before, the failure was rethrown, so acatchthat emitted ran on a closed cubit and threw aStateError. guardeddrops an operation's synchronous throw, like its later failure, whenclose()follows in the same turn. Before, the throw reached the caller afterclose().guardedcompletes withnullwhen the operation returns a future that calls back synchronously, such as Flutter'sSynchronousFuture(a cachedAssetBundle.loadStructuredData, for example), andclose()is called in the same turn. Before, it returned the value on a closed cubit, and a plainemitafter the null check threw aStateError. Fordart:asyncfutures the result and its timing do not change, with one exception: a future that had already failed in another error zone now completes the call like any other failure. Before, the call never completed.BlocSelectorWithBlocfollows a replaced provided bloc also when its element was already dirty: the old bloc emitted a state that changed the selection, and the provided bloc was replaced before the next frame while the widget instance was reused, for example aconstchild ofBlocProvider.value. Before, it kept showing and listening to the old bloc, also after later replacements of the provided bloc.BlocSelectoritself still behaves the old way (flutter_bloc9.0.0 and 9.1.2).
- A failure that arrives just before the run is cancelled, superseded or
its bloc closed, while the caller has not resumed yet, is dropped like a
value:
- Deprecated, removed in 1.0:
- the extension
BlocContextExtensionand itsreadOrNull,watchOrNull,selectOrNullandwithBloc. The extension is annotated as well, soshow BlocContextExtensionin an import is reported too; effectWhenofBlocEffectListenerandBlocConsumerWithEffects, and the typedefEffectCondition;RestartableTask.run: itsTbelongs to the class and cannot take the boundT extends Object, so itsnullstays ambiguous;BlocEffectListener.withChild, which only serves the deprecatedMultiEffectListener;- the typedefs
BlocEffectListenerWithBloc, which has an unused type parameter and no replacement, andBlocSelectedCondition, the same function type asBlocCondition.
- the extension
- Docs:
- The README leads with the async helpers for Cubits and the effects; the "Policies" section is now "Conditions".
- New in the README: a table of which async helper to use; recipes for a
flow with several
awaits, for "ignore while running" and for widget tests with a mocked cubit, whoseeffectshas to be stubbed; "Compared with" (bloc_presentation,CancelableOperation,bloc_concurrency); and "Versioning", the policy from 1.0.0. The async sample usesRestartableTasksMixinalone and clears its loading flag when the latest run fails. - Corrected: without type arguments,
BlocEffectListenergivesonEffectanObject?effect at every language version, not only below 3.7.BlocConsumerWithEffectsinfersSandEfrombloc:at language version 3.7 or later, which is the language version of the app. - The dartdoc of
emitEffectsays that aBlochandler cancelled by a transformer still delivers its effect unless it checksemit.isDone. - The dartdoc of
EffectsSource.effectssays what a hand-written implementation must return: a broadcast stream that never emits an error. - The example app models its effects as
sealedclasses. - pub.dev: the description mentions the effects, and the topic
effectsreplaceswidgets.
Migration impact:
-
A
catcharoundrunOutcome,runLatestOutcome,runLatestorCancellationToken.runno longer sees a failure whose run was cancelled before the caller resumed; that run takes the cancelled path instead. -
Deprecated APIs keep working; the analyzer reports a use as a
deprecated_member_useinfo, which failsflutter analyzeuntil migrated:context.readOrNull<B>()->context.read<B?>();watchOrNull<B>()->watch<B?>();selectOrNull<B, S, T>((state) => state.x)->select<B?, T?>((bloc) => bloc?.state.x), orbloc == null ? null : ...when the selector is not a member chain;withBloc((B bloc) => bloc.x)->read<B?>()?.x, or a local variable and a null check when the callback is more than one member access. These lookups ofproviderreturn the same values, with the same rebuilds.package:flutter_bloc/flutter_bloc.dartexports them andbloc_plusdoes not: a file without that import needs it, and drops thebloc_plusimport when it usedbloc_plusonly for the helpers.effectWhen: (effect) => effect is Sub->if (effect is! Sub) return;orif (effect case Sub(...))at the top ofonEffect, which also promotes the effect type.RestartableTask.run(task)->runOutcome((_) => task()), andif (!outcome.isCompleted) return;beforeoutcome.value.listener.withChild(child)->child:in the constructor, or the listener inMultiBlocListener, which supplies the child.BlocSelectedCondition<T>->BlocCondition<T>;BlocEffectListenerWithBloc<B, S, E>->void Function(BuildContext context, B bloc, E effect).
-
A class that extends or implements
CancellationTokenorRestartableTask, a mock of either written by hand or with mocktail (implements), and amixin X oneither of them no longer compile (invalid_use_of_type_outside_library). mockito refuses to generate a mock of afinalclass. Use real instances: a test createsCancellationToken()and callscancel(), or runs its work through a realRestartableTask. -
Move
voidand nullable work offrunLatest,guardedandCancellationToken.run:-
instead of
runLatest, userunLatestOutcomeand check the outcome before anything else. Without the check, the code after it runs for a superseded run as well, so the analyzer reports an outcome that is awaited and dropped:// Before await runLatest('save', save); emit(saved); // After final outcome = await runLatestOutcome('save', (_) => save()); if (!outcome.isCompleted) return; // superseded or closed emit(saved); -
guardedandCancellationToken.runhave no outcome twin: await the work plainly and then check what the method checked, before anything else. Forguardedthat isisClosed, whichsafeEmitchecks for you; forCancellationToken.runit istoken.isCancelled, whichsafeEmitdoes not check. Return a non-null value, such as a record, only to keep what the two methods add: the work does not start on a closed bloc or a cancelled token, its later failure is dropped, andCancellationToken.runreleases its caller atcancel()instead of when the work ends.
-
-
A generic helper that forwards its own type parameter needs the same bound (
Future<T?> load<T extends Object>(...)), and so do an override ofrunLatestorguardedand a function type that names the old signature. -
The analyzer does not report a helper that returns the call (
=> runLatest(key, task),=> guarded(task),=> token.run(task)):flutter analyzestays clean, and the compiler fails with "Inferred type argument 'T' doesn't conform to the bound 'Object' of the type variable 'T'". After upgrading, compile the app or runflutter test. -
A
BlocdropsSafeEmitMixinand checksisClosed, which is whatsafeEmitandguardedchecked.isClosedistruefrom the call ofclose(), butclose()cancels the handlers a few microtasks later, or, while any handler of the bloc usessequential(), only after the running and the queued handlers have finished. Until then the handler'semitstill delivers. Inside a handler:-
safeEmit(state)becomesif (!isClosed) emit(state);, which now also callsonTransition. In theonDataandonErrorofemit.onEachthat is the same check.emit.forEachemits every state its callbacks return, so a check there cannot stop the emit: where a value must not arrive afterclose(), useemit.onEach; -
await guarded(operation)becomesif (isClosed) return;beforeawait operation()and again after it. The first check keeps the operation from starting on a closed bloc, after an earlierawaitor in an event thatsequential()queued beforeclose(); -
guardedalso dropped a failure that arrives afterclose(): putif (isClosed) return;first in thecatch, andrethrowotherwise.on<Load>((event, emit) async { if (isClosed) return; try { final item = await repository.load(event.id); if (isClosed) return; emit(state.copyWith(item: item)); } catch (_) { if (isClosed) return; rethrow; } });
A public method of the
Bloc, and a callback that outlives its handler, such as a stream subscription, adds an event instead (if (!isClosed) add(event)) with a handler that emits: the state then changes when that handler runs, not during the call. Checkingemit.isDoneas well stops a handler that a transformer cancelled, whichguardednever did. -
-
A direct subclass of
BlocBaseextendsCubitinstead, or checksisClosedbeforeemitby hand. -
BlocBuilderWithBlocandBlocListenerWithBlocneed no change in ordinary use, and akeythat was added only to switch between an explicit and a provided bloc can go. Code that relied on them staying with the old instance passes that instance asbloc:. Code that typed them asBlocBuilderBaseorBlocListenerBase, calledbuild(context, state)or readlisteneras a(context, state)callback adapts:buildtakes only the context, andlisteneris the(context, bloc, state)callback. The callbacks get the context of the innerBlocBuilderorBlocListener. -
None for
BlocListenerWithBlocwithout achild, for the replaced bloc ofBlocSelectorWithBlocand forguardedwith a synchronous future. -
A call of those six methods from outside the bloc class, such as
isTaskRunningread inbuild,cancelLatestcalled from a widget, or a call from an extension on the bloc or from a function outside the class, gets two analyzer warnings (invalid_use_of_protected_memberandinvalid_use_of_visible_for_testing_member), soflutter analyzefails. Move the call into a method of the bloc, and keep what the UI shows, such as a loading flag, in the state, as the async example in the README does. A method that cancels the run, such ascancelPreviewin the example app, clears that flag itself: the cancelled call completes with a cancelled outcome, ornullfromrunLatest, and leaves the state as it is. The bloc, its subclasses, amixin X on RestartableTasksMixin<S>oron SafeEmitMixin<S>, and files undertest/,integration_test/andtest_driver/may still call them; a test helper underlib/may not. -
An
awaitofrunLatest,runLatestOutcome,guarded,CancellationToken.runorRestartableTask.runOutcomeas a statement, which drops the result, gets anunused_resultwarning, soflutter analyzefails. Check the result before acting on the run:if (!outcome.isCompleted) return;, orif (result == null) return;for the methods that complete withnull. Only when the call is the last thing in the method and the task emits itself, as in the README recipe for a flow with severalawaits, return the future instead:Future<void> open() async => runLatestOutcome(...), or a method withoutasyncthat ends withreturn runLatestOutcome(...);. In a closure, such as the handler of aBloc, use=>orasync =>: a block body that returns the future gets thevoid_checkslint. In a method with atryor an earlyreturn;, keepawaitand check the result: a returned future escapes thecatchand thefinally, andreturn;does not compile onceasyncis gone. A future that is returned, assigned or passed to a function such asunawaitedis not reported.
Release type rationale:
minor: breaking changes of the class hierarchy, of three method signatures, of the classes thatSafeEmitMixinapplies to, of the superclasses of two widgets, of where six methods may be called without analyzer warnings and of five methods whose dropped result is now reported, which a 0.x minor allows, and deprecations. A constraint such as^0.3.1does not resolve to 0.4.0, so nothing changes until a project raises it.
0.3.1 #
- Added:
debugPrintUnheardEffects: set it totrueandemitEffectprints a warning in debug builds for an effect that nothing listens to. Effects are not replayed, so such an effect is lost, for example one emitted from the bloc's constructor or before the listening widget is mounted. Off by default; release builds never print it.- README: a recipe for testing effects in unit and widget tests.
Migration impact:
- None.
Release type rationale:
patch: one additive, opt-in debug flag (a new public top-level variable) and docs; nothing changes unless the flag is set. Under the 0.x convention^0.3.0already allows it; code that uses the flag needs^0.3.1.
0.3.0 #
- Added:
BlocCondition<S>andwhenChanged(selector, {equals}). The result goes straight intobuildWhen,listenWhenandselectorShouldRebuild, also onBlocBuilder,BlocListenerandBlocConsumer, without type arguments when the widget has its own. Select a record for several fields; passequals:for collections.BlocEffectListener<B extends EffectsSource<E>, E>: a wrong effect type or a bloc without effects no longer compiles, and the listener composes insideMultiBlocListener.RestartableTask.runOutcomeandRestartableTasksMixin.runLatestOutcome: the task gets aCancellationToken, and theTaskOutcome<T>result tells a cancelled run apart from one that completed withnull.CancellationToken.whenCancelledcan abort the underlying I/O.BlocConsumerWithEffects.listeneris optional.- A
constconstructor forBlocListenerWithBloc.
- Changed:
- A cancelled, superseded or closed run releases its caller at once (
nullorTaskOutcome.cancelled()) instead of waiting for the abandoned work, which keeps running. This fixes callers that hung on work that never completes. BlocConsumerWithEffectsrequiresB extends HasEffects<S, E>.- The
*WithBlocwidgets and their callback typedefs acceptB extends StateStreamable<S>, like flutter_bloc's widgets.readOrNull,watchOrNullandwithBlocaccept any provided type, such as a repository:withBloc((Repo repo) => ...)now finds the repository instead of inferringNeverand returningnull.selectOrNullaccepts anyStateStreamableSource<S>, the typeBlocProviderprovides and keeps up to date. BlocConsumerWithBlocandBlocConsumerWithEffectsresolve the bloc once per build, so states, effects and every callback come from one instance, also right afterbloc:changes from an instance tonull.emitEffectandsafeEmitare@protectedand@visibleForTesting, likeemit.- New direct dependency:
provider>=6.0.0 <7.0.0, the rangeflutter_blocalready requires.
- A cancelled, superseded or closed run releases its caller at once (
- Deprecated, removed in 1.0:
RebuildPolicy,ListenPolicyand their 12 factories (includingwhenListen, which clashes withbloc_test),EffectListener,MultiEffectListenerandSingleChildEffectListener.
Migration impact:
- Deprecated APIs keep working; each use is a
deprecated_member_useinfo, which failsflutter analyzeuntil migrated:onChange(sel)/onChangeListen(sel)->whenChanged(sel), keeping<S, T>when the widget has no type arguments; the...Byforms ->whenChanged(sel, equals: eq);whenRebuild(p)/whenListen(p)->p;always()-> omit the parameter;never()->(previous, current) => false;distinct()->(previous, current) => previous != current(omitting the parameter differs only for a first emitted state equal to the initial one);a.and(b)-> a plain predicate or a record selector.EffectListener<B, S, E>->BlocEffectListener<B, E>;MultiEffectListener->MultiBlocListener, which needs a non-empty list; a listener for one effect subtype -> the supertype withif (effect case Sub(...))inonEffect.- With
bloc_test, importbloc_pluswithhide whenListenuntil 1.0.
BlocConsumerWithEffectsno longer compiles with a bloc that implementsEffectsSourceby hand: mix inHasEffects<S, E>.emitEffectandsafeEmitcalled from outside the bloc, extension methods on it included, now warn (tests are exempt): move the call into the bloc or into amixin X on HasEffects<S, E>.- Code after the
awaitof a superseded run, afinallyincluded, now runs while the newer run is in flight: check the outcome before resetting a shared loading flag. - In a
Blochandler, a task that calls the handler'semitstill needs anemit.isDone(ortoken.isCancelled) check: the handler now completes first, and bloc rejects the lateemitonly with an assert, so release builds emit the stale state. - Write both type arguments of
BlocEffectListener: below language version 3.7,Eis not inferred frombloc:. - After
bloc:ofBlocConsumerWithBlocorBlocConsumerWithEffectschanges from an instance tonull, the widget follows the provided bloc at once instead of the previous instance.BlocBuilderWithBlocandBlocListenerWithBlockeep the previous instance, likeBlocBuilderandBlocListener, while their callback gets the provided one: give them a newkeywhen you switch.
Release type rationale:
minor: new APIs, wider type bounds and deprecations; the narrower consumer bound, the new analyzer warnings, the earlier release of superseded callers and the consumers following the provided bloc are behaviour changes that a 0.x minor allows.
0.2.2 #
- Fixes:
CancellationToken.run,RestartableTask.run,runLatestandguardeddrop the failure of superseded or cancelled work like its result; only the latest run can throw.guardedno longer starts on a closed bloc.HasEffects.close()no longer waits for a paused effect subscriber before closing the bloc.BlocSelectorWithBlocbehaves likeBlocSelector: no stale value after the selector changes, one selector call per state change, andselectorShouldRebuildgets the last built value asprevious.readOrNull,watchOrNullandselectOrNullreturnnullonly when no provider exists.runLatestdrops the keys of failed tasks; a repeatedclose()waits for the first one.bloclower bound raised to9.2.1, sosafeEmitandguardedalso stop on a closingBloc.
- Tooling: Flutter 3.50 support (
flutter_lints^6.0.0, contributors need Dart 3.8; example app onmaterial_ui, Flutter >=3.47), one gated CI workflow that also checks the lowest dependency versions and Flutter 3.10.6, contract tests and clearer API docs. Package minimums stay at Dart 3.0 and Flutter 3.10.
Migration impact:
- No API changes; if you pin
blocbelow9.2.1, upgrade within9.x. - Superseded or cancelled runs, and
guardedcalls that fail after close, returnnullinstead of throwing. - Effects emitted right before
close()reach subscribers after the bloc is closed, like its last states; a subscriber that emits into the bloc in response should usesafeEmit. selectorShouldRebuildgets the last built value asprevious;BlocSelectorWithBlocis now aStatefulWidget.- A missing provider read inside a bloc's
createnow throws fromreadOrNull/watchOrNull/selectOrNullinstead of returningnull.
Release type rationale:
patch: bug fixes without API changes.
0.2.1 #
- Compatibility metadata update:
- lowered the developer tooling floor from
Dart 3.8toDart 3.0by constrainingflutter_lintsto the latest line that still supports Dart 3.0 - kept the package minimum SDKs unchanged at
Dart >=3.0.0andFlutter >=3.10.0
- lowered the developer tooling floor from
Migration impact:
- No API changes. No migration required.
Release type rationale:
patchchange for compatibility metadata and tooling support only.
0.2.0 #
- Added policy composition and custom equality helpers:
whenRebuildwhenListenRebuildPolicy.and,RebuildPolicy.or,RebuildPolicy.notListenPolicy.and,ListenPolicy.or,ListenPolicy.notonChangeByonChangeListenBy
- Expanded effect ergonomics:
- added
effectWhentoEffectListener - added
MultiEffectListener
- added
- Added higher-level async helpers:
RestartableTasksMixin- keyed
runLatest,cancelLatest,cancelAllLatest,isTaskRunning
- Added
BlocConsumerWithEffectsfor combined state and effect composition. - Updated README, PRD, task specs, and example app to document the new APIs.
Migration impact:
- No breaking API changes. Existing code continues to work.
- Consumers can adopt the new APIs incrementally.
Release type rationale:
minorbump for new public API surface additions.
0.1.3 #
- Documentation improvements:
- Added dartdoc comments for the public API to improve generated package docs and pub.dev documentation coverage.
Migration impact:
- No API changes. No migration required.
Release type rationale:
patchbump for user-visible documentation improvements with no behavior changes.
0.1.2 #
- Documentation cleanup:
- Removed the two trailing README sections:
StatusandRelease process (without verified publisher).
- Removed the two trailing README sections:
- Change category:
chore
Migration impact:
- No API changes. No migration required.
Release type rationale:
patchbump for documentation-only cleanup.
0.1.1 #
- CI improvements:
- Added dedicated coverage workflow with Codecov upload.
- Coverage upload now supports
CODECOV_TOKENvia GitHub Actions secret.
- Release process improvements:
- Added PR quality and release automation workflows.
- Added manual publish workflow for non-verified publisher setup.
- Documentation improvements:
- Added status badges to README.
- Clarified release flow and publish steps.
Migration impact:
- No API changes. No migration required.
Release type rationale:
patchbump for CI, release automation, and documentation improvements.
0.1.0 #
- Added
ui_with_blocmodule:BlocBuilderWithBlocBlocListenerWithBlocBlocConsumerWithBlocBlocSelectorWithBloc
- Added
context_extensionsmodule:readOrNullwatchOrNullselectOrNullwithBloc
- Added
policiesmodule:- Rebuild policies:
distinct,onChange,always,never - Listen policies:
distinctListen,onChangeListen,alwaysListen,neverListen
- Rebuild policies:
- Added
async_safetymodule:SafeEmitMixinCancellationTokenRestartableTask
- Added
effectsmodule:HasEffectsEffectListener
Migration impact:
- First feature release, no migration required.
Release type rationale:
minorbump due to new public API surface additions.