Saad
Contact

Flutter Operations Part II: Dart Zones & Unrepresentation

Table of Contents 7 sections

This code compiled without a single complaint:

dart
final SuccessOperation<User> op = SuccessOperation.empty();
op.data; // StateError: No data available in an empty operation.

The field is typed as a non-null <User>. Reading it throws. The compiler signed off on a promise the runtime had no intention of keeping.

You might reflexively say: “Just do <User?>”, but that defeats the point of my flutter_operations package.

If you’ve ever called snapshot.requireData on a FutureBuilder and been rewarded with a crash, you’ve met this exact species of bug: a getter whose type says “always here” guarding a value that’s only sometimes here. It’s everywhere in Dart code. And for a year, it was in mine.

A little over a year ago, I wrote Exhaustive Pattern Matching for Exhausted Flutter Developers. The whole thesis: use Dart’s sealed classes to make illegal states unrepresentable, so the compiler catches what discipline can’t.

That article became flutter_operations, a small package that wraps the loading/error/data dance in a sealed OperationState<T> hierarchy with exhaustive pattern matching. It has held up well. The core idea, four sealed states, cached data flowing through loading and error, exhaustive switches in the build method, hasn’t moved an inch.

But the snippet above is real 1.x behavior, and it wasn’t an accident; it was a design decision. Two of the package’s deliberate design decisions, in fact, kept generating friction in real projects. Both had good reasons to exist. And both turned out to have problems I hadn’t accounted for.

Version 2.0 redesigns both, and this article is the reasoning in full: what each design was for, what broke down in practice, what replaced it, and, most importantly, the two pieces of Dart knowledge that made the replacements possible.

Design Decision #1: The Empty Success State

Some operations succeed without producing anything. A delete, a logout, a fire-and-forget confirmation. Some operations succeed and legitimately have nothing to give you: “who is the current user?” when nobody is signed in.

These are real cases; I hit them constantly in my own apps. So 1.x modeled them as a first-class state:

dart
final class SuccessOperation<T> extends OperationState<T> {
  const SuccessOperation({required T super.data, this.message})
      : empty = false;

  /// Creates an empty success state, indicating the operation completed
  /// successfully but returned no data.
  const SuccessOperation.empty({this.message})
      : empty = true,
        super(data: null);

  /// Whether the operation completed successfully but returned no data.
  final bool empty;

  /// Throws [StateError] if this is an empty operation.
  @override
  T get data {
    if (empty) {
      throw StateError('No data available in an empty operation.');
    }
    return _data as T;
  }
}

Success with data and success without data are both success, so they should be the same state with a flag. One constructor for each, an `empty` flag to branch on, and a `data` getter that stays non-null for the common case. On paper, tidy.

What practice had to say

The friction arrived on a schedule.

First, the getter. SuccessOperation<User>.data is typed as a non-null User, but if the state was constructed with .empty(), reading it throws a StateError at runtime. The type signature makes a promise the runtime can’t keep. Every consumer of the state had to know to check empty before touching data.

“Had to know” was the ENTIRE premise of the original article and accompanying package.

Second, the flag started leaking. Version 1.4.0 of the changelog is, in hindsight, a case study: == crashed when comparing empty states, because it called the throwing getter. hasData threw. toString() threw. Emitting SuccessOperation.empty() from a Cubit broke state comparison.

Each fix was small. Collectively, they were a signal that the class was fighting its own shape.

Third, and this is the one that screamed in my face the most: look at what the class actually contains. Two fields, empty and _data, that must be kept mutually consistent by convention. A getter whose safety depends on the caller checking a flag first. Loose fields, kept in sync by discipline, guarded by a runtime trap. Hypocrisy in my own work.

That’s the isLoading / error / data pattern. The one from the first paragraph of the original article. It had quietly reappeared one level down, inside the success state, wearing a constructor as a disguise.

bool empty is the boolean-flag problem all over again; the sealed hierarchy solved it between states and the flag reintroduced it within one.

Once I saw it that way, the fix stopped being “patch the getter again” and became “find the model where this state doesn’t need a flag at all.” And the model was already sitting in the type parameter.

Crash Course: Letting T Speak

How do you model “successful but no data” without a flag and a runtime trap?

You don’t. You let the type parameter model it because it already can!

This is the part of the article where I’d like you to briefly forget about the package, because this applies to any generic result type you’ll ever design.

There are exactly three shapes of “success” an operation can have, and Dart can spell all three:

Shape 1: Success always carries a value: This is your ordinary fetch. Parameterize with a non-nullable type and data is guaranteed, by the compiler, forever:

dart
OperationState<List<Post>> // data is List<Post>. Not maybe. Not unless-empty.

Shape 2: Success may legitimately carry nothing: Current user when signed out. The winning bid when there are no bids. This is not an “empty success”; this is a success whose value is nullable, and Dart has first-class syntax for that:

dart
OperationState<User?> // data is User?, and null is a disgusting but honest answer.

Shape 3: Success never carries anything: Delete, logout, PIN confirmation. The operation is fire-and-forget by definition, and Dart has a type for “there is nothing here” too:

dart
OperationState<void> // there was never going to be data.

That third one surprises people. void is a perfectly legal type argument in Dart. Future<void> never bothered anyone; OperationState<void> is the same statement applied to state: “this operation’s success has no payload, and the compiler should stop anyone who tries to read one”.

Note

This is different from the Dart default of <dynamic>, which allows “any” value, while <void> disallows any values.

You literally cannot use a void value; the language forbids it.

Notice what happens to SuccessOperation.empty() in this framing: it dissolves. The cases it was juggling with a runtime flag become different type arguments, chosen once, at the declaration, checked at compile time. Here’s the pattern-matching before and after:

dart
switch (state) {
  // 1.x: the flag decides, at runtime, hope you checked it!! Sure would be a shame if you hadn't!
  SuccessOperation(empty: true) => const Text('Done'),
  SuccessOperation(:var data) => DataView(data), // throws if you got it wrong. Teehee, woopsie-daisies! :>

  // 2.0 with OperationState<User?>: null is part of the type
  SuccessOperation(data: null) => const Text('Signed out'),
  SuccessOperation(:var data?) => UserView(data),

  // 2.0 with OperationState<void>: there is nothing to match on
  SuccessOperation() => const Text('Deleted'),
}

Same expressiveness. Zero runtime traps. The compiler now enforces what the empty flag used to ask you, politely, to enforce yourself.

The constructor trick

One detail worth stealing for your own APIs. The base class stores T? _data, because loading and error states genuinely may have no data (they carry an optional cache). But SuccessOperation’s constructor narrows it:

dart
sealed class OperationState<T> {
  const OperationState({T? data}) : _data = data;
  final T? _data;
}

final class SuccessOperation<T> extends OperationState<T> {
  // `T super.data`, not `T? super.data`. That one character is the API.
  const SuccessOperation({required T super.data, this.message});

  @override
  T get data => _data as T; // safe: the constructor made it impossible otherwise
}

That required T super.data is a super parameter with a tightened type. SuccessOperation<User>(data: null) is now a compile-time error at the call site. BUT: SuccessOperation<User?>(data: null) is fine! Because you said so in the type argument. The getter’s downcast can never fail, because the only door into the class checks the invariant.

The 1.x getter enforced the invariant with a throw. The 2.0 constructor enforces it with a type. Same rule, but moved from your stack trace to your IDE’s squiggly line. This is the whole philosophy of the redesign in one line of parameter syntax.

Design Decision #2: The Optional Message Channel

SuccessOperation has an optional message field, for when your server returns { “data”: …, “message”: “Saved!” } and you’d like to toast that message alongside the payload. The question is how the message gets from your fetch() into the state.

The 1.x answer: a second override. The common case stays pristine; you override fetch() and never think about input parameters or return types associated with multi-data payloads. If you do want a message, you override fetchWithMessage() instead and return a Dart record:

dart
@override
Future<(User, String?)> fetchWithMessage() async {
  final response = await api.getUser();
  return (response.data, response.message);
}

The reason I wrote this in the first place is because it was a very real feature from the server’s API that I needed to preserve in my job, and didn’t have a meaningful way to return a message plainly in my original API, hence this function’s existence.

Why two functions instead of just making the default fetch return an object that can hold an optional message? Several reasons actually, but the main rationale was: don’t tax the common case for a feature most screens/devs don’t use.

That reasoning was sound as far as it went. The problem is what it cost structurally: since you were meant to override exactly one of the two methods; not both, not none; neither could be abstract. Both got default bodies that throw, and the mixin had to figure out your intent at runtime:

dart
// 1.x internals: runtime detection of which method you overrode.
try {
  resultWithMessage = await fetchWithMessage();
} on _NotImplementedException {
  // fetchWithMessage not overridden, fall back to fetch()
}
// ...and separately validate that BOTH weren't overridden:
throw StateError(
  'Both fetch() and fetchWithMessage() are overridden. '
  'You must override exactly one of them.',
);

So you, as a developer using this package, needed to KNOW that you MUST override one of fetch or fetchWithMessage, and if you didn’t, oopsie!

What practice had to say

Living with this across real projects surfaced a familiar pattern of friction:

  1. Forget to override either method? Compiles fine. Explodes on first-load. Boo!
  2. Override both by accident, say, during a refactor that half-migrated a widget? Compiles fine. Explodes at runtime. Boo!
  3. Want to add a message to an existing fetch()? Rewrite the signature, wrap the return value in a record, restructure every return statement. A one-line feature costs a method migration. Boo!
  4. The happy path runs exception-probing machinery on every load, to check a rule the compiler used to check for free. Boo!

That last point deserves the emphasis. Before the message feature existed, fetch() was effectively mandatory and missing it was caught at compile time. Aka: The Entire Point Of The Package!

Adding the second method demoted that to a runtime check. The API traded away a compile-time guarantee to gain an optional feature. I knew this was an issue, but I couldn’t think of a way around it in Dart at the time.

The record signature was the other tell. (T, String?) leaked into every override that wanted messages, but the message isn’t really part of the result; it’s a side note about the result. Forcing it into the return type made the signature carry information that only the mixin cared about.

So the design goal for 2.0 wrote itself: fetch() stays exactly Future<T>, always, for everyone; there is one method, and it is abstract. The code inside the fetch gets an optional side channel to hand the mixin a string, without the signature ever knowing.

A side channel that threads through async code without appearing in any signature. Dart has a mechanism built for precisely this, and almost nobody uses it.

Crash Course: Zones

If you’ve encountered Zones at all, it was probably one line of boilerplate: runZonedGuarded in main(), catching uncaught errors for Crashlytics or some logging thingy that you were told to do in some online docs. Or perhaps your AI agent used it, and you never questioned it because it looked complicated and fancy. Copy, paste, never think about it again.

The intuitive way you think Zones work: Any code that throws an uncaught exception inside a Zone’s closure will be caught, like a super try-catch.

But a Zone is much more interesting than a crash net. A Zone is the execution context for asynchronous code. Every callback, every microtask, every await continuation runs inside some zone, and zones form a tree: when you schedule async work, the resulting callbacks run in the zone that scheduled them.

They also have a secret hidden feature you didn’t know about: Zones also carry zone values!
An immutable key-value map you provide when creating one. Any code running in that zone (or a child of it) can read those values through Zone.current:

dart
const userKey = Object();

void whoAmI(String label) {
  print('$label: ${Zone.current[userKey]}');
}

Future<void> main() async {
  await runZoned(() async {
    whoAmI('before await'); // before await: Saad Ardati
    await Future<void>.delayed(const Duration(seconds: 1));
    whoAmI('after await');  // after await: Saad Ardati
  }, zoneValues: {userKey: 'Saad Ardati'});
}

Look at the second print. whoAmI was called after an await, in a continuation scheduled onto the event loop, and it still sees “Saad Ardati”. The value follows the asynchronous flow of control, through awaits, through nested function calls, without appearing in a single function signature.

If you’re a Flutter developer, you already have the right mental model for this:

Zone values are to your async call stack what InheritedWidget is to your widget tree.

Theme.of(context) gives any widget access to ambient data without threading a ThemeData parameter through forty constructors. Zone.current[key] gives any function access to ambient data without threading a parameter through forty signatures. Same trick, different tree. (Java people know it as ThreadLocal; Python people as contextvars. Dart is single-threaded per isolate, so the zone tree plays the role the thread would.)

This is exactly the shape of the message problem. The mixin wants to offer fetch() an optional mailbox. The mailbox should be invisible when unused, reachable from anywhere inside the fetch (including after awaits, including three helper functions deep), and it must never touch the method’s signature.

attachMessage: A Side Channel With No Signature Tax

Here’s the entire 2.0 message API from the user’s side:

dart
class _UserState extends State<UserWidget> with AsyncOperationMixin<User, UserWidget> {
  @override
  Future<User> fetch() async {
    final response = await api.getUser();

    if (response.serverMessage case final message?) attachMessage(message);

    return response.data;
  }
}

fetch() returns Future<User>. No record. No second method. Don’t need a message? Don’t call attachMessage, and the API surface you see is exactly one method. fetchWithMessage(), streamWithMessage(), the record signatures, and the runtime detection are all gone.

Under the hood it’s small enough to quote almost in full. The mixin allocates one mutable cell per `load()` call and runs your fetch inside a zone carrying it:

dart
class MessageCell {
  String? value;
}

FutureOr<void> load({bool cached = true}) async {
  final currentGeneration = ++_generation;
  setLoading(cached: cached);

  final cell = MessageCell();
  try {
    final result = await runZoned(
      () => fetch(),
      zoneValues: {messageKey: cell},
    );
    if (!mounted || _generation != currentGeneration) return;
    setSuccess(result, message: cell.value);
  } catch (exception, stackTrace) {
    // ... ErrorOperation as usual
  }
}

void attachMessage(String message) {
  final cell = Zone.current[messageKey];
  if (cell case MessageCell cell?) cell.value = message;
}

attachMessage just asks “is there a mailbox in my current zone?” and drops the string in it. When the fetch resolves, the mixin reads the cell and pairs the message with the SuccessOperation. Called outside a load()? The lookup returns null and it becomes a harmless no-op.

Streams get the same channel with one extra rule: call attachMessage before each yield, and each message pairs with that emission. The mixin reads and clears the cell synchronously at the top of its onData listener, before any awaits, so async* back-pressure keeps message and value in lockstep:

dart
@override
Stream<Message> stream() async* {
  await for (final raw in chatService.messagesStream()) {
    if (raw.serverMessage case final message?) attachMessage(message);
    yield raw.data;
  }
}

Why not just an instance field?

This is the question I expect from anyone who’s read this far, because there’s a tempting three-line alternative: put String? _pendingMessage on the mixin as a field, have attachMessage write to it, have load() read it after the fetch. Why zones? Literally why even bother? It even passes the demo test.

Now let a user double-tap the refresh button.

Two load() calls are in flight, sharing one field. Fetch A (slow) calls attachMessage(‘A saved’) late in its life; fetch B (fast) has already started. The mixin’s generation counter correctly discards A’s result, but A’s message-write isn’t gated by anything; it lands in the shared field just in time to get paired with B’s success state. The user did action B and got a toast about action A. Good luck reproducing that from a bug report.

You could fix it with more discipline: clear the field at the right moments, tag writes with a generation, add a comment begging future maintainers not to touch it. Or you apply the same principle that drove the success-state redesign:

Don’t guard shared state; make the sharing unrepresentable.

The most bullet-proof software you will ever use is the one that makes bugs impossible to exist retroactively.

Each load() creates its own cell and its own zone. Fetch A’s attachMessage resolves, through Zone.current, to fetch A’s cell; it cannot see B’s cell, because A’s code never runs in B’s zone. There’s no clearing logic and no cross-talk to prevent, because the two calls never share a mailbox in the first place. Sealed classes made illegal states unrepresentable; zone-scoped cells make illegal inter-leavings unrepresentable. The same philosophy, applied to time instead of shape.

Unrepresentation is the entire point of this package. It’s a pattern worth noticing in your own libraries: sometimes the API improvement you’re looking for is the impossibility of a bug to ever happen instead of guarding against it.

And fetch() is abstract again

With the dual-override gone, fetch() and stream() became plain abstract methods. Forget to implement one, and your IDE yells at you. The compile-time guarantee that the message feature had demoted to a runtime check is restored; and it took removing a feature, not adding one, to get it back.

Migrating from 1.5.x

This is a breaking release, and the fixes are mostly mechanical, with one semantic trap.

SuccessOperation.empty() is gone. Pick the type parameter that matches what the operation actually models instead.

dart
// Fire-and-forget (delete, logout):
// before: Cubit<OperationState<DeleteResult>> + SuccessOperation.empty()
class DeleteCubit extends Cubit<OperationState<void>> {
  void run() {
    // ...
    emit(const SuccessOperation(data: null));
  }
}

// Legitimately optional (current user when signed out):
// before: Cubit<OperationState<User>> + SuccessOperation.empty()
class CurrentUserCubit extends Cubit<OperationState<User?>> {
  void signOut() => emit(const SuccessOperation(data: null));
}

fetchWithMessage() / streamWithMessage() are gone. Move the message to attachMessage and un-record your return type:

dart
// before
@override
Future<(User, String?)> fetchWithMessage() async {
  final response = await api.getUser();
  return (response.data, response.message);
}

// after
@override
Future<User> fetch() async {
  final response = await api.getUser();
  if (response.message case final message?) attachMessage(message);
  return response.data;
}

Everything else, the four states, the pattern-matching styles, loadOnInit, globalRefresh, the convenience getters, is untouched. The full changelog with every case is on pub.dev.

The Same Disclaimer as Always

Nothing about 2.0 changes the package’s mission statement, so I’ll restate it before anyone gets ideas: flutter_operations is not your next global state management solution. It’s still a pragmatic utility for async operations scoped to a single widget; the dialogs, the settings pages, the changelog screens. The moment you need multiple coordinated operations or testable business logic, graduate to Bloc, Riverpod, or whatever your team has standardized on, exactly as the original article said at considerably greater length.

It coexists; it does not compete. In fact, my favorite state management cocktail has lately been, and what this article may have hinted at: Cubits with <OperationState>. BLoC + Flutter Operations.