<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Italo Matos on Medium]]></title>
        <description><![CDATA[Stories by Italo Matos on Medium]]></description>
        <link>https://medium.com/@italomatos.developer?source=rss-df835ac90624------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*S_24GnMbmGugZnOk</url>
            <title>Stories by Italo Matos on Medium</title>
            <link>https://medium.com/@italomatos.developer?source=rss-df835ac90624------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:47:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@italomatos.developer/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[State Management + Security: Why Sensitive Data Needs a Runtime, Not Just State]]></title>
            <link>https://systemweakness.com/state-management-security-why-sensitive-data-needs-a-runtime-not-just-state-e580dafa37a1?source=rss-df835ac90624------2</link>
            <guid isPermaLink="false">https://medium.com/p/e580dafa37a1</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Italo Matos]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 19:43:48 GMT</pubDate>
            <atom:updated>2026-04-14T08:03:32.135Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A practical idea inspired by Ekklesia Worship: handling passwords, OTPs, tokens, and session persistence with explicit lifecycle rules.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LADXS3MWQgBlKOuD" /></figure><p>When we talk about state management in Flutter, the conversation usually revolves around rebuilds, observability, immutability, dependency injection, side effects, events, and async state.</p><p>All of that matters.</p><p>But there is another question that, in my view, still doesn’t sit at the center of the discussion nearly enough:</p><p><strong>what happens to sensitive data after it enters state?</strong></p><p>That question became impossible for me to ignore while working on <strong>Ekklesia Worship</strong>, a product I’m building to help churches create worship playbacks and lyric-based media. Even though the core of the product is media creation, once you introduce authentication, cloud sync, marketplace access, session restore, and account flows, the architecture starts dealing with much more than screens and UI updates.</p><p>It starts dealing with things like:</p><ul><li>passwords</li><li>OTP codes</li><li>access tokens</li><li>refresh tokens</li><li>authenticated session restore</li><li>logout cleanup</li></ul><p>And those values do not behave like ordinary UI state.</p><ul><li>A password typed into a login screen should not simply stay in memory until someone remembers to overwrite it.</li><li>An OTP should not remain around after verification.</li><li>An access token should not be treated the same way as a page filter or a selected tab.</li><li>A refresh token should not just be another string stored somewhere because “the app needs it later.”</li></ul><p>That was the point where I started thinking beyond traditional state management. Not about replacing it. But about complementing it with something else:</p><p><strong>a runtime that understands the lifecycle of sensitive data.</strong></p><h3>The problem starts when session becomes “just another object”</h3><p>In many real apps, session-related logic gets distributed across multiple places.</p><p>A little in the ViewModel, a little in a service, a little in a repository, a little in dispose logic, a little in some manual clear() call someone added after a successful login… It works… until it doesn’t.</p><p>The issue is not that the rules do not exist. The issue is that they are often <strong>implicit. </strong>And when important rules are implicit, they are easier to forget, easier to duplicate, and easier to implement inconsistently.</p><p>For example, a typical app may need to answer questions like:</p><ul><li>Should the session survive app restarts?</li><li>Which part of the session can be persisted?</li><li>Should the access token be restored automatically?</li><li>Should the refresh token be restored only explicitly?</li><li>What should be cleared on logout?</li><li>What should disappear when the screen is disposed?</li><li>What should be masked in logs?</li><li>What should never be serialized?</li></ul><p>These are not only state questions. These are <strong>retention, cleanup, expiration, persistence, and exposure</strong> questions. That is why I started thinking about this as more than state management.</p><h3>This is not about “security magic”</h3><p>Before going any further, I want to be very clear about what this idea is <strong>not</strong>. This is <strong>not</strong> about claiming perfect security.</p><p>It does not magically wipe memory at a cryptographic level.</p><p>It does not protect against debuggers.</p><p>It does not protect against compromised devices.</p><p>It does not solve memory dumps or Dart’s internal string copies.</p><p>It does not eliminate every possible exposure vector.</p><p>That would be dishonest. What this tries to improve is something much more practical: <strong>safe handling</strong>.</p><p>That means:</p><ul><li>reducing accidental retention</li><li>avoiding unintended persistence</li><li>making expiration explicit</li><li>making cleanup intentional</li><li>controlling exposure in logs and debug tools</li><li>separating UI state from sensitive runtime data more clearly</li></ul><p>That alone is already very valuable in real applications.</p><h3>State management answers one question well. Sensitive data needs another.</h3><p>Over time, I found it useful to separate two concerns.</p><h4>State management</h4><p>Usually answers questions like:</p><ul><li>what changed?</li><li>who is observing this?</li><li>when should the UI rebuild?</li><li>how do I represent loading, success, and error?</li></ul><h4>State runtime</h4><p>Answers different questions:</p><ul><li>how long should this value live?</li><li>when should it be cleared?</li><li>can it be persisted?</li><li>should it be restored automatically or explicitly?</li><li>should it be redacted in logs?</li><li>should it live only in memory?</li></ul><p>In my view, those two things do not compete. They complement each other. Traditional state management is great at modeling UI behavior. But for sensitive data, there is often a second layer of concern that remains manual and scattered across the app.</p><p>That second layer is what I started calling <strong>State Runtime</strong>.</p><h3>A real case: Ekklesia Worship</h3><p>Ekklesia Worship is not an “auth app.” It is a media creation product for churches.</p><p>Its core goal is to help users create worship playbacks, lyric-based visual content, and song media in a more organized and professional way.</p><p>But once features like cloud synchronization, account access, templates, and marketplace capabilities are introduced, authentication and session handling become part of the architecture too.</p><p>That made the problem concrete.</p><p>The product now includes flows like:</p><ul><li>login</li><li>account creation</li><li>password recovery</li><li>OTP verification</li><li>authenticated session restore</li><li>logout</li></ul><p>And suddenly the app is no longer dealing only with content state. It is also dealing with <strong>sensitive lifecycle</strong>. That was the practical context that pushed me to explore this idea more seriously.</p><h3>SafeData: turning sensitive values into explicit contracts</h3><p>The core thought was simple: What if a value like a password or OTP was not just a raw field inside state? What if it also carried an explicit lifecycle policy?</p><p>That led me to explore a primitive like this:</p><pre>final password = SafeData&lt;String?&gt;(<br>  initialValue: typedPassword,<br>  policy: const SafeDataPolicy(<br>    clearOnDispose: true,<br>    clearOnCommandSuccess: {&#39;login&#39;},<br>    logStrategy: SafeDataLogStrategy.redacted,<br>  ),<br>);<br><br>final otpCode = SafeData&lt;String?&gt;(<br>  policy: const SafeDataPolicy(<br>    clearOnDispose: true,<br>    clearOnCommandSuccess: {&#39;verifyOtp&#39;},<br>    expiresAfter: Duration(seconds: 30),<br>    persistence: SafeDataPersistence.memoryOnly,<br>    logStrategy: SafeDataLogStrategy.masked,<br>  ),<br>);</pre><p>The change looks small, but conceptually it is huge. The password is no longer just a String?. The OTP is no longer just a temporary field. They become values with <strong>retention rules</strong>.</p><p>This makes it possible to model sensitive data as something the architecture actively understands, not something the app only happens to store.</p><h3>What this changes in practice</h3><h4>1. Passwords</h4><p>A password usually has one of the shortest useful lifecycles in the entire app. It needs to exist:</p><ul><li>while the user types it</li><li>while the login request is in progress</li></ul><p>After a successful login, keeping that value around usually makes no sense. With an explicit policy, the runtime can clear that password automatically after the login command succeeds.</p><p>That removes one more “don’t forget to clean this up later” rule from scattered application code.</p><h4>2. OTP codes</h4><p>OTP codes are an even clearer example of ephemeral data. They often need:</p><ul><li>short expiration</li><li>automatic cleanup after success</li><li>cleanup on screen disposal</li><li>masked or redacted logging</li></ul><p>Without explicit lifecycle handling, OTP values tend to remain available simply because nobody removed them.</p><p>By giving them a runtime policy, their behavior becomes part of the architecture instead of a convention.</p><h4>3. Access tokens</h4><p>Access tokens often make sense only as short-lived in-memory session values.</p><ul><li>They should not necessarily be serialized by default.</li><li>They should not necessarily remain attached to a ViewModel beyond the active session.</li><li>They should not show up raw in logs or debug tooling.</li></ul><p>This is not just a <strong>state question</strong>. It is a <strong>runtime retention question</strong>.</p><h4>4. Refresh tokens</h4><p>Refresh tokens usually require a different lifecycle altogether.</p><p>Unlike passwords or OTPs, they may need:</p><ul><li>secure persistence</li><li>controlled restoration</li><li>explicit deletion on logout</li><li>redacted logging</li></ul><p>And that distinction matters. Because not all sensitive values should be treated the same way. That is one of the strongest reasons why “state” alone often feels too broad as a model.</p><h3>Session persistence is where this becomes really useful</h3><p>The part of this idea that felt most valuable to me was not password cleanup by itself.</p><p>It was <strong>session persistence</strong>. That is where the runtime mindset really starts to show its worth. A more explicit session model might look like this:</p><ul><li><strong>password: </strong>temporary, clear after login</li><li><strong>OTP: </strong>temporary, expiring, clear after verification</li><li><strong>access token: </strong>memory only</li><li><strong>refresh token: </strong>optionally persisted in secure storage</li><li><strong>session metadata: </strong>regular state</li><li><strong>restore: </strong>explicit and controlled</li><li><strong>logout: </strong>centralized cleanup of everything</li></ul><p>For example:</p><pre>final accessToken = SafeData&lt;String?&gt;(<br>  policy: const SafeDataPolicy(<br>    clearOnDispose: true,<br>    persistence: SafeDataPersistence.memoryOnly,<br>    logStrategy: SafeDataLogStrategy.redacted,<br>  ),<br>);<br><br>final refreshToken = SafeData&lt;String?&gt;(<br>  policy: const SafeDataPolicy(<br>    clearOnDispose: true,<br>    persistence: SafeDataPersistence.secureStorage,<br>    logStrategy: SafeDataLogStrategy.redacted,<br>  ),<br>);</pre><p>At that point, the session is no longer just an object you happen to store somewhere. It becomes a composition of values with different rules, and that is exactly the kind of nuance that generic state containers usually do not model by themselves.</p><h3>Explicit secure persistence should be optional, not accidental</h3><p>One important design choice that came out of this thinking was separation. I do not think secure persistence should be silently bundled into the core of a state package as a default side effect, instead, I think it makes more sense to keep that capability explicit and optional. That is why the idea naturally expanded into something like a separate package:</p><ul><li><strong>flutter_stasis</strong> for runtime-aware state management</li><li><strong>flutter_stasis_secure</strong> for optional secure persistence bindings</li></ul><p>Something along these lines:</p><pre>final binding = SafeDataSecureBinding&lt;String&gt;(<br>  field: refreshToken,<br>  adapter: adapter,<br>  key: &#39;refresh_token&#39;,<br>  encode: (value) =&gt; value,<br>  decode: (value) =&gt; value,<br>);</pre><p>Again, the important part is not the exact API. It is the principle:</p><p><strong>sensitive persistence should happen because the architecture chose it explicitly, not because the whole state object was serialized by accident.</strong></p><h3>A real flow: login &gt;&gt; OTP &gt;&gt; authenticated session &gt;&gt; restore &gt;&gt; logout</h3><p>The most useful way to look at this is as a full flow.</p><h4>Step 1 — Login</h4><p>The user types email and password. The password enters the runtime as a sensitive value. It exists only while needed, is redacted in logs, and is cleared after a successful login command.</p><h4>Step 2 — OTP verification</h4><p>If the account requires two-factor verification, the OTP enters as another sensitive runtime value. It can expire after a short time and clear itself automatically after success.</p><h4>Step 3 — Authenticated session</h4><p>The app now receives session data. The access token can remain memory-only. The refresh token may be bound to secure storage if the app wants persistent session restore.</p><h4>Step 4 — Session restore</h4><p>When the app starts again, session restoration does not need to be some vague side effect. It can be explicit, controlled, and testable.</p><h4>Step 5 — Logout</h4><p>Logout becomes a single architectural cleanup point. It can clear:</p><ul><li>password remnants</li><li>OTP values</li><li>access token</li><li>refresh token in memory</li><li>refresh token in secure persistence</li></ul><p>That kind of explicitness makes the whole auth flow easier to reason about and harder to accidentally mishandle.</p><h3>But don’t Riverpod, Bloc, and others already solve this?</h3><p>They solve important parts of the problem very well.</p><p>Riverpod, Bloc, Provider, MobX, Signals, and other approaches are all valuable depending on what you need.</p><p>They help a lot with things like:</p><ul><li>reactivity</li><li>state composition</li><li>dependency injection</li><li>side effects</li><li>predictable UI updates</li><li>architecture boundaries</li></ul><p>The point here is <strong>not</strong> that they are wrong or insufficient as state managers. The point is narrower:</p><p>in most projects, the lifecycle of sensitive data still ends up being handled <strong>manually by the application</strong>. That means even with an excellent state manager, you still need to decide:</p><ul><li>when to clear a password</li><li>when OTP expires</li><li>how to avoid unintended persistence</li><li>how to avoid raw exposure in logs</li><li>how to restore tokens in a controlled way</li><li>how to centralize cleanup on logout</li></ul><p>That is the gap this idea is trying to explore. Not <strong>“better reactivity”. </strong>Not <strong>“better state management”. </strong>But a more explicit model for <strong>sensitive data lifecycle</strong>.</p><h3>A light comparison, not a benchmark</h3><p>If I were to compare this conceptually, I would frame it like this:</p><ul><li>most state managers answer <strong>“what changed?”</strong></li><li>what I am trying to explore is also <strong>“how long should this sensitive value live?”</strong></li></ul><p>That is not an attack on existing tools. It is a different architectural concern.</p><p>And in real products, especially anything involving auth, session restore, account recovery, or tokens, that concern keeps showing up whether we model it explicitly or not.</p><p>So the question is not whether apps need to handle it. They already do. The real question is whether we want that logic to stay implicit and scattered, or whether we want to make it a first-class part of the runtime.</p><h4>What this improves</h4><p>I think the practical value of this approach is easy to miss if you focus only on the abstraction name.</p><p>The real improvements are things like:</p><ul><li>less accidental retention</li><li>less unintended persistence</li><li>clearer cleanup rules</li><li>more explicit expiration behavior</li><li>safer debug output</li><li>more centralized logout cleanup</li><li>better testability of lifecycle decisions</li><li>less auth-sensitive logic scattered across multiple layers</li></ul><p>In other words, the gain is not “perfect security.” The gain is <strong>less architectural ambiguity</strong>. And that matters a lot.</p><h4>What this does not solve</h4><p>It is just as important to be clear about what this approach does <strong>not</strong> solve.</p><p>It does not guarantee:</p><ul><li>resistance against debuggers</li><li>safety on compromised devices</li><li>protection against memory dumps</li><li>cryptographic zeroization of strings</li><li>absolute secrecy inside the runtime</li></ul><p>Those are different layers of the problem. What this approach tries to improve is:</p><ul><li>lifecycle clarity</li><li>retention discipline</li><li>cleanup discipline</li><li>controlled persistence</li><li>reduced accidental exposure</li></ul><p>That is already a meaningful step forward without pretending to solve more than it does.</p><h4>Why this matters to me</h4><p>What made this worth exploring for me is that it turned an “implementation detail” into an architectural question. Before this, cleanup rules for sensitive data often lived in comments, conventions, and “we should remember to…”</p><p>After this line of thinking, those rules started to feel like something that deserved to be modeled explicitly. That is what I find interesting about the idea of a State Runtime. It is not about replacing state management.</p><p>It is about recognizing that some data — especially passwords, OTPs, tokens, and session artifacts — carry lifecycle requirements that deserve first-class treatment.</p><h3>Conclusion</h3><p>State management solves a lot. But for sensitive data, it does not always answer the most important question: <strong>how should this value live?</strong></p><p>Passwords, OTPs, access tokens, refresh tokens, and session restore are not just “more state.”</p><p>They have retention rules.</p><p>They have cleanup rules.</p><p>They have persistence constraints.</p><p>They have exposure risks.</p><p>That is why I started exploring ideas like SafeData, optional secure bindings, and the broader notion of <strong>State Runtime</strong> in the Stasis ecosystem. Maybe the real question is not whether a state manager should “do security.”</p><p>Maybe the more useful question is this: <strong>should a state architecture completely ignore the lifecycle of sensitive data?</strong></p><p>I do not think it should.</p><p>Link for Packages:<br><a href="https://pub.dev/packages/flutter_stasis_secure">https://pub.dev/packages/flutter_stasis_secure</a><br><a href="https://pub.dev/packages/flutter_stasis">https://pub.dev/packages/flutter_stasis</a><br><a href="https://github.com/DIMAAGR/flutter_stasis">https://github.com/DIMAAGR/flutter_stasis</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e580dafa37a1" width="1" height="1" alt=""><hr><p><a href="https://systemweakness.com/state-management-security-why-sensitive-data-needs-a-runtime-not-just-state-e580dafa37a1">State Management + Security: Why Sensitive Data Needs a Runtime, Not Just State</a> was originally published in <a href="https://systemweakness.com/">System Weakness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The problem with storing navigation and snackbars in state]]></title>
            <link>https://medium.com/@italomatos.developer/the-problem-with-storing-navigation-and-snackbars-in-state-29643144694b?source=rss-df835ac90624------2</link>
            <guid isPermaLink="false">https://medium.com/p/29643144694b</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Italo Matos]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 19:03:17 GMT</pubDate>
            <atom:updated>2026-03-26T19:03:17.328Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>By Ítalo Souza Matos — Flutter Developer</strong></p><p>Every Flutter app eventually needs to do three things from a ViewModel: show a snackbar, navigate to another screen, open a dialog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5a2qUb6tXxy-SE5q0GtRBw.png" /></figure><p>The obvious approach is to put that in state:</p><pre>class ProfileState {<br>  final bool isLoading;<br>  final String? successMessage;   // show snackbar when non-null<br>  final String? navigationRoute;  // navigate when non-null<br>}</pre><p>It works — until it doesn’t.</p><h3>The problem with state-based side effects</h3><p>When you store a navigation intent or snackbar message in state, you immediately have a new question: <strong>when do you clear it?</strong></p><p>If you clear it immediately after the UI consumes it, you have a race condition — the widget might not have read it yet.</p><p>If you clear it on the next action, it re-fires on rebuild. A screen rotation, a setState somewhere up the tree, a didUpdateWidget — and suddenly the snackbar shows again, or the user navigates twice.</p><pre>// The &quot;clear it after&quot; pattern — fragile<br>class ProfileViewModel extends ChangeNotifier {<br>  String? _successMessage;<br><br>  void save() async {<br>    await _repository.save();<br>    _successMessage = &#39;Saved!&#39;;<br>    notifyListeners();<br>    // Clear after a frame? After what delay?<br>    // What if the widget was destroyed before reading it?<br>    Future.delayed(Duration.zero, () {<br>      _successMessage = null;<br>      notifyListeners();<br>    });<br>  }<br>}</pre><p>This is a consume-and-clear protocol you have to invent and maintain per event, per screen.</p><h3>What an ephemeral event actually is</h3><p>A snackbar, a navigation command, a dialog trigger — these aren’t <strong>state</strong>. State describes what the screen currently looks like. A “show snackbar” intent describes something that should happen <strong>once</strong>, right now, and then disappear.</p><p>The right model for this is a <strong>stream</strong>, not a value.</p><pre>State  →  &quot;the screen is loading&quot;      (persists until it changes)<br>Event  →  &quot;show this snackbar now&quot;     (consumed once, gone)</pre><p>This is what one-shot UI events solve: separate the channel for side effects from the channel for persistent state.</p><h3>How it works in practice</h3><p>In flutter_stasis, every ViewModel has two channels:</p><ul><li>stateListenable — a ValueListenable for state that widgets observe</li><li>events — a Stream for one-shot UI events</li></ul><p>The ViewModel dispatches events; the View reacts:</p><pre>// Define your events as sealed classes<br>sealed class ProfileEvent extends UiEvent {<br>  const ProfileEvent();<br>}<br><br>final class ShowSnackBarEvent extends ProfileEvent {<br>  const ShowSnackBarEvent(this.message);<br>  final String message;<br>}<br><br>final class NavigateToHomeEvent extends ProfileEvent {<br>  const NavigateToHomeEvent();<br>}</pre><pre>// ViewModel emits — no UI knowledge<br>class ProfileViewModel extends StasisViewModel&lt;AppFailure, Profile, ProfileState&gt; {<br>  Future&lt;void&gt; save() =&gt; execute(<br>    command: _saveUseCase,<br>    onSuccess: (profile) {<br>      setSuccess(profile);<br>      emit(const ShowSnackBarEvent(&#39;Profile saved&#39;));<br>      emit(const NavigateToHomeEvent());<br>    },<br>  );<br>}</pre><pre>// View reacts — no state mutation needed<br>StasisEventListener(<br>  stream: vm.events,<br>  onEvent: (context, event) async {<br>    switch (event) {<br>      case ShowSnackBarEvent(:final message):<br>        ScaffoldMessenger.of(context)<br>            .showSnackBar(SnackBar(content: Text(message)));<br>      case NavigateToHomeEvent():<br>        context.go(&#39;/home&#39;);<br>    }<br>  },<br>  child: ProfileScreen(vm: vm),<br>);</pre><p>No consume-and-clear. No race conditions. The event fires once and the stream moves on.</p><h3>The problem with broadcast streams and tabs</h3><p>There’s a subtlety that matters in real apps: <strong>broadcast streams don’t remember who’s listening</strong>.</p><p>In a tab-based navigation (GoRouter’s StatefulShellRoute, for example), ViewModels are often singletons — created once and reused. But the widgets that listen to them get rebuilt every time you switch tabs.</p><p>With a broadcast stream, each new StasisEventListener that mounts subscribes independently. If two instances are active at the same time (which can happen during transitions), both receive the same event. Snackbar shows twice. User navigates twice.</p><p>The solution is to make the channel aware of who’s listening:</p><pre>// Instead of using the raw stream, bind with an owner key<br>StasisEventListener(<br>  channel: vm.eventChannel,<br>  ownerKey: &#39;home_shell&#39;,         // dedupe key<br>  onEvent: (context, event) async { ... },<br>  child: child,<br>);</pre><p>When a new listener binds with the same ownerKey, the previous subscription is replaced. No duplicates, no manual cleanup beyond normal widget disposal.</p><h3>Single-consumer by default</h3><p>In flutter_stasis 0.3.0, the default event channel mode is singleConsumer — not broadcast. This means the framework warns you in debug mode if more than one listener is active at the same time.</p><pre>// If you intentionally want multiple listeners (e.g. shell + child view):<br>class MyViewModel extends StasisViewModel&lt;F, S, T&gt; {<br>  MyViewModel() : super(<br>    MyState.initial(),<br>    uiEventMode: UiEventMode.broadcast,<br>  );<br>}</pre><p>The default makes architectural mistakes visible immediately, while the escape hatch exists for cases that genuinely need it.</p><h3>Why this matters beyond snackbars</h3><p>One-shot events are the right model for anything that should happen once in response to an action:</p><ul><li>Navigation after form submission</li><li>Show a dialog when something goes wrong</li><li>Trigger a haptic feedback</li><li>Start an animation that shouldn’t replay on rebuild</li><li>Log an analytics event exactly once</li></ul><p>All of these share the same property: they’re not state. They don’t describe what the screen looks like — they describe something that should happen. A stream models that intent correctly. A value in a state object does not.</p><h3>The principle</h3><blockquote><strong><em>State describes the screen. Events describe what should happen.</em></strong></blockquote><p>If you find yourself writing if (state.message != null) { showSnackbar(); clearMessage(); }, you&#39;re storing an event in state. Move it to a stream.</p><p><strong>flutter_stasis</strong> is available on pub.dev. The source is on GitHub at <a href="https://github.com/DIMAAGR/flutter_stasis">github.com/DIMAAGR/flutter_stasis</a>.</p><p><em>Ítalo Souza Matos is a Flutter Developer and Tech Lead with 4+ years building mobile applications for fintechs, healthtechs and POS systems in Brazil.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29643144694b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I got tired of BLoC boilerplate. So I built my own state manager.]]></title>
            <link>https://medium.com/@italomatos.developer/i-got-tired-of-bloc-boilerplate-so-i-built-my-own-state-manager-2978641946f9?source=rss-df835ac90624------2</link>
            <guid isPermaLink="false">https://medium.com/p/2978641946f9</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react-state-management]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Italo Matos]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 20:30:52 GMT</pubDate>
            <atom:updated>2026-03-21T20:41:26.584Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n2qTJsz3o_ExLgdF" /></figure><h3>After years with MobX, BLoC and ValueNotifier, I built a leaner alternative — explicit lifecycle, standardised async, and ephemeral UI events.</h3><p><strong>By Ítalo Souza Matos — Flutter Developer</strong></p><p>I’ve been building Flutter apps for over four years. Fintechs, healthtechs, POS systems, crypto wallets. In every single project, the same problem kept showing up.</p><p>Not a hard problem. Not a clever architectural challenge. Just… tedium.</p><pre>// Event<br>class LoadProjects extends ProjectEvent {}<br></pre><pre>// State<br>class ProjectState {<br>  final bool isLoading;<br>  final List&lt;Project&gt;? data;<br>  final String? error;<br>  // constructor, copyWith...<br>}</pre><pre>// Bloc<br>class ProjectBloc extends Bloc&lt;ProjectEvent, ProjectState&gt; {<br>  ProjectBloc() : super(ProjectState(...)) {<br>    on&lt;LoadProjects&gt;((event, emit) async {<br>      emit(state.copyWith(isLoading: true));<br>      try {<br>        final result = await repository.getProjects();<br>        emit(state.copyWith(isLoading: false, data: result));<br>      } catch (e) {<br>        emit(state.copyWith(isLoading: false, error: e.toString()));<br>      }<br>    });<br>  }<br>}</pre><p>Three files. A try/catch I’ve written a hundred times. A state object that can be isLoading: false and data: null at the same time without anyone complaining.</p><p>I tried Riverpod. The mental model of ref.watch, ref.read, ref.listen, ref.invalidate clicked for some people. It never fully clicked for me. I tried MobX — powerful, but the codegen started feeling like a tax I paid every time I changed something.</p><p>So I built Stasis.</p><h3>The idea</h3><p>I wanted three things:</p><p><strong>1. A state lifecycle that’s impossible to get wrong.</strong></p><p>Not isLoading + hasError + data. A sealed type. Either loading, or success with data, or error with a failure. Never both at once.</p><p><strong>2. One standard way to run async work.</strong></p><p>No more try/catch copy-pasted everywhere. One method that handles loading, success, and error the same way every time.</p><p><strong>3. UI events that don’t pollute state.</strong></p><p>When you want to show a snackbar or navigate after an action, you shouldn’t be storing that in the state object. It’s a one-shot thing. Fire and forget.</p><h3>How it works</h3><p>Every screen gets a StasisViewModel and a StateObject. That&#39;s the whole model.</p><p>The StateObject is immutable and owns two things: the lifecycle state (loading, success, error, initial) and whatever fields your screen needs.</p><pre>class ProjectsState extends StateObject&lt;AppFailure, List&lt;Project&gt;, ProjectsState&gt; {<br>  const ProjectsState({<br>    required super.state,<br>    this.filter = ProjectFilter.all,<br>  });<br><br>  final ProjectFilter filter;<br><br>  // Derived from lifecycle — never duplicated<br>  List&lt;Project&gt;? get projects    =&gt; dataOrNull;<br>  String?        get errorMessage =&gt; failureOrNull?.message;<br><br>  @override<br>  ProjectsState withState(ViewModelState&lt;AppFailure, List&lt;Project&gt;&gt; state) =&gt;<br>      copyWith(state: state);<br><br>  ProjectsState copyWith({...}) =&gt; ...;<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [state, filter];<br>}</pre><p>Notice errorMessage is a getter derived from failureOrNull. You don&#39;t store the error message separately — it lives inside ErrorState. If you&#39;re in LoadingState, failureOrNull returns null. No inconsistency possible.</p><p>The StasisViewModel wraps the state and exposes execute — the one method that runs everything:</p><pre>class ProjectsViewModel<br>    extends StasisViewModel&lt;AppFailure, List&lt;Project&gt;, ProjectsState&gt; {<br><br>  ProjectsViewModel(this._getProjects) : super(ProjectsState.initial());<br><br>  final GetProjectsUseCase _getProjects;<br><br>  Future&lt;void&gt; load() =&gt; execute(<br>    command: _getProjects,<br>    onSuccess: setSuccess,<br>    onLoading: setLoading,<br>    // onError omitted → setError is called automatically<br>  );<br><br>  void setFilter(ProjectFilter f) =&gt;<br>      update((s) =&gt; s.copyWith(filter: f));<br>}</pre><p>onError is optional. If you don&#39;t pass it, setError is called automatically. If you want custom behaviour — say, showing a snackbar instead of rendering an error banner — you override it:</p><pre>Future&lt;void&gt; load() =&gt; execute(<br>  command: _getProjects,<br>  onSuccess: setSuccess,<br>  onError: (f) =&gt; emit(ShowSnackBarEvent(f.message)),<br>);</pre><p>Which brings me to events.</p><h3>UI events — keeping navigation out of state</h3><p>The ViewModel doesn’t know anything about the UI. It doesn’t import Navigator, doesn’t touch ScaffoldMessenger. It just emits a typed event and the view reacts.</p><pre>// Define events in your feature<br>final class ShowSnackBarEvent extends UiEvent {<br>  const ShowSnackBarEvent(this.message);<br>  final String message;<br>}<br><br>final class NavigateToHomeEvent extends UiEvent {<br>  const NavigateToHomeEvent();<br>}d</pre><pre>// ViewModel fires<br>void onSaved() {<br>  emit(const ShowSnackBarEvent(&#39;Project saved&#39;));<br>  emit(const NavigateToHomeEvent());<br>}</pre><pre>// View reacts — nothing about navigation lives in state<br>StasisEventListener(<br>  stream: vm.events,<br>  onEvent: (context, event) async {<br>    switch (event) {<br>      case ShowSnackBarEvent(:final message):<br>        ScaffoldMessenger.of(context)<br>            .showSnackBar(SnackBar(content: Text(message)));<br>      case NavigateToHomeEvent():<br>        Navigator.of(context).pushReplacementNamed(&#39;/home&#39;);<br>    }<br>  },<br>  child: ...,<br>);</pre><p>BLoC handles this with streams and listeners. Riverpod uses ref.listen. Both work, but neither makes it as explicit as a sealed UiEvent type that the compiler checks for you.</p><h3>Granular rebuilds with StasisSelector</h3><p>StasisBuilder rebuilds the whole tree when any part of the state changes. That&#39;s fine for simple screens. For complex ones — say, a screen with a waveform animating while a drag overlay reacts to drag events — you want more control.</p><pre>// Only rebuilds when isDragging changes<br>StasisSelector&lt;AudioState, bool&gt;(<br>  listenable: vm.stateListenable,<br>  selector: (state) =&gt; state.isDragging,<br>  builder: (context, isDragging, _) =&gt; DropZone(active: isDragging),<br>);<br><br>// Only rebuilds when waveform data changes<br>StasisSelector&lt;AudioState, List&lt;double&gt;&gt;(<br>  listenable: vm.stateListenable,<br>  selector: (state) =&gt; state.waveform,<br>  equals: (a, b) =&gt; a.length == b.length,<br>  builder: (context, waveform, _) =&gt; WaveformWidget(points: waveform),<br>);</pre><p>Same idea as BLoC’s buildWhen or Riverpod&#39;s select, but as a standalone widget you can nest anywhere in the tree.</p><h3>Race conditions without the boilerplate</h3><p>Every async UI has race conditions. The user taps a button twice. A search fires while the previous one is still running. Stasis handles this through CommandPolicy:</p><pre>// Ignore the second tap while the first is in flight<br>Future&lt;void&gt; submit() =&gt; execute(<br>  command: _submitUseCase,<br>  onSuccess: setSuccess,<br>  policy: CommandPolicy.droppable,<br>);<br><br>// Cancel the previous search, run the latest<br>Future&lt;void&gt; search(String query) =&gt; execute(<br>  command: TaskCommand(() =&gt; _searchUseCase(query)),<br>  onSuccess: setSuccess,<br>  policy: CommandPolicy.restartable,<br>);</pre><p>bloc_concurrency does this too and does it well. I wanted the same thing built into the execution model instead of as a separate package.</p><h3>Works with dartz — or without it</h3><p>If your use cases return Future&lt;Either&lt;Failure, T&gt;&gt;, there&#39;s an optional adapter:</p><pre>// flutter_stasis_dartz<br>Future&lt;void&gt; load() =&gt; executeEither(<br>  command: _getProjects.call,<br>  onSuccess: setSuccess,<br>);</pre><p>If you don’t use dartz, wrap anything in a TaskCommand:</p><pre>Future&lt;void&gt; load() =&gt; execute(<br>  command: TaskCommand(() async {<br>    try {<br>      return CommandSuccess(await _getProjects());<br>    } on NetworkException catch (e) {<br>      return CommandFailure(AppFailure(e.message));<br>    }<br>  }),<br>  onSuccess: setSuccess,<br>);</pre><p>Or implement Command directly on your use case and pass it straight through — no wrapper needed.</p><h3>Testing</h3><pre>import &#39;package:flutter_stasis_test/flutter_stasis_test.dart&#39;;<br><br>test(&#39;load emits loading then success&#39;, () async {<br>  final vm = ProjectsViewModel(mockUseCase);<br><br>  await assertStateSequence(<br>    listenable: vm.stateListenable,<br>    act: vm.load,<br>    expected: [<br>      (s) =&gt; s.isLoading,<br>      (s) =&gt; s.projects?.isNotEmpty == true,<br>    ],<br>    includeInitial: false,<br>  );<br>});</pre><p>No streams to mock, no events to fire. Call the method, assert the states. That’s it.</p><h3>The packages</h3><p>The ecosystem is split so you only take what you need:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/035dec4b9c81c0e10bdc314e28c9b451/href">https://medium.com/media/035dec4b9c81c0e10bdc314e28c9b451/href</a></iframe><p>Package What it is flutter_stasis_core Pure Dart — no Flutter dependency flutter_stasis Flutter widgets and ViewModel flutter_stasis_dartz Optional dartz adapter flutter_stasis_test Test helpers</p><h3>Is this going to replace BLoC?</h3><p>No. BLoC has years of community, documentation, DevTools integration, and a massive ecosystem. If your team already knows it well, there’s no reason to switch.</p><p>What Stasis offers is a different trade-off: less structure, less boilerplate, more explicit state. One ViewModel, one StateObject, one way to run async work. If that sounds like what you want, give it a try.</p><p><strong>flutter_stasis</strong> is available on pub.dev. The source is on GitHub at <a href="https://github.com/DIMAAGR/flutter_stasis">github.com/DIMAAGR/flutter_stasis</a>.</p><p>If you build something with it, I’d genuinely like to know. Open an issue, send a PR, or just drop a comment here.</p><p><em>Ítalo Souza Matos is a Flutter Developer and Tech Lead with 4+ years building mobile applications for fintechs, healthtechs and POS systems in Brazil.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2978641946f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>