<?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 Ali Wajdan on Medium]]></title>
        <description><![CDATA[Stories by Ali Wajdan on Medium]]></description>
        <link>https://medium.com/@aliwajdan?source=rss-ce9f546e2aa5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qmmb9spN0U_MsgCN</url>
            <title>Stories by Ali Wajdan on Medium</title>
            <link>https://medium.com/@aliwajdan?source=rss-ce9f546e2aa5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 15:49:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aliwajdan/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[The Supabase Bug That Locked Out Users Who Hid Their Apple Email]]></title>
            <link>https://aliwajdan.medium.com/the-supabase-bug-that-locked-out-users-who-hid-their-apple-email-df33a116b7b0?source=rss-ce9f546e2aa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/df33a116b7b0</guid>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[apple-sign-in]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Ali Wajdan]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 10:01:03 GMT</pubDate>
            <atom:updated>2026-09-05T10:01:03.407Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ejhOEBpBfcys6Cpg0G0JQw.jpeg" /><figcaption>An iPhone prompting Sign in with Apple beside a laptop showing the Supabase dashboard used to trace the login bug. Image generated via <a href="https://gemini.google.com/">Gemini</a></figcaption></figure><blockquote>Apple sends a user’s email only once, on the very first Sign in with Apple request. Miss that moment in Supabase and some users never get back in.</blockquote><p>Three users emailed support the same week, all with the same complaint. They could sign in with Apple, watch the loading spinner, and land right back on the onboarding screen every single time. No error. No crash. Supabase said they were authenticated. My app disagreed.</p><p>Sign in with Apple had worked on <a href="https://apps.apple.com/pk/app/dreamybot/id6743409461">DreamyBot</a> since launch. App Store review passed it, real users used it every day, and nobody had complained until that week. The bug only showed up for people who reinstalled the app or switched phones, which is exactly the group a two week QA pass never covers. The root cause was not in my authentication code. It was in what Apple sends, and what it stops sending after the first time.</p><h4>Apple Only Tells You Once</h4><p>Apple hands over a user’s email and full name exactly once, on the very first authorization for your app. Every login after that, whether it is a new device, a reinstall, or a token refresh after the user revokes and re-grants access in Settings, arrives without that data. The <strong>id_token</strong> Supabase receives on those later logins can carry an empty email claim.</p><p>That is fine if you captured the email the first time and never asked Apple again. It breaks if any part of your flow reads the live session’s email on every launch, which is exactly what one line of my onboarding check did. The first login passed because Apple included the email. Every login after that, from a new device, failed the same check without a sound, and the user landed back in onboarding with nothing on screen to explain why.</p><p>Users who chose Hide My Email made it worse. Their private relay address, something like <a href="/service/mailto:abc123@privaterelay.appleid.com">abc123@privaterelay.appleid.com</a>, only exists on that first payload too. Lose it, and there is no way to ask Apple for it a second time.</p><h4>Store It Once, Stop Asking Apple</h4><p>The fix was to stop treating Apple’s token as a source of truth on every login and start treating it as one only at signup. I added a trigger on auth.users that copies the email and name into a profiles table the moment the row is created, then pointed every part of the app that needed that data at profiles, never at the live session.</p><pre>create function public.handle_new_user()<br>returns trigger<br>language plpgsql<br>security definer<br>as $$<br>begin<br>  insert into public.profiles (id, email, full_name)<br>  values (<br>    new.id,<br>    new.email,<br>    new.raw_user_meta_data -&gt;&gt; &#39;full_name&#39;<br>  )<br>  on conflict (id) do nothing;<br>  return new;<br>end;<br>$$;<br><br>create trigger on_auth_user_created<br>  after insert on auth.users<br>  for each row execute procedure public.handle_new_user();</pre><p>This runs once, on insert, at the exact moment Apple’s payload is guaranteed to be complete. Every later login, even one carrying no email claim at all, leaves the row alone.</p><pre>// Wrong: reads Apple&#39;s live session on every launch<br>final email = supabase.auth.currentSession?.user.email;<br><br>// Right: reads the row written once at signup<br>final profile = await supabase<br>    .from(&#39;profiles&#39;)<br>    .select(&#39;email, full_name&#39;)<br>    .eq(&#39;id&#39;, userId)<br>    .single();<br><br>final email = profile[&#39;email&#39;] as String?;</pre><p>Onboarding checks the profile row now, not the token. A user who signed up with Apple two months ago and opens the app on a new phone today still gets through, because the email was never anyone’s job to fetch twice.</p><ul><li>Apple sends a user’s email and full name once, on the first authorization only. Later logins can arrive with that field empty.</li><li>If any part of your Supabase auth flow reads the session email on every launch, a second device or a reinstall will fail silently.</li><li>Capture identity data in a trigger on auth.users insert, not in application code that runs on every login.</li><li>Test Sign in with Apple with a reinstall and a second device, not just a fresh signup. That is where this bug lives.</li><li>Private relay emails are just as fragile. If you did not store one on the first login, Apple will not hand it to you again.</li></ul><p>Nobody flagged this in code review, because the code was correct. It read a real field on a real object. The field was just empty for a reason nothing in the codebase explained. That is the part that got me. A working line of code, built on a wrong assumption about when Apple actually sends data.</p><p>If you have run into a version of this with Apple, Google, or any provider that only shares data once, I would like to hear how you caught it.</p><p>I write about Flutter and Supabase from real production bugs like this one, once or twice a week. Follow along if that is useful.</p><p><strong>AUTHOR BIO</strong><br>Ali Wajdan is a Senior Mobile Engineer with 5+ years of experience shipping apps used by people across iOS and Android. I build cross-platform mobile apps, AI-integrated backends, and everything in between.</p><p>Portfolio: <a href="https://aliwajdan.com/">https://aliwajdan.com</a><br>LinkedIn: <a href="https://www.linkedin.com/in/aliwajdanpasha/">https://www.linkedin.com/in/aliwajdanpasha</a><br>GitHub: <a href="https://github.com/aliwajdan453">https://github.com/aliwajdan453</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df33a116b7b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On-Device AI in Flutter Sounds Free. TFLite Cost Me 40MB and 3 Days]]></title>
            <link>https://aliwajdan.medium.com/on-device-ai-in-flutter-sounds-free-tflite-cost-me-40mb-and-3-days-7d2f93feca76?source=rss-ce9f546e2aa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d2f93feca76</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ali Wajdan]]></dc:creator>
            <pubDate>Fri, 04 Sep 2026 10:01:04 GMT</pubDate>
            <atom:updated>2026-09-04T10:01:04.208Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jkpJ-TMqZ4hCMo9wQ7l71g.jpeg" /><figcaption>A phone running an app offline on a clinic desk, the everyday setting where a stable connection can’t be assumed. Image generated via <a href="https://gemini.google.com/">Gemini</a></figcaption></figure><blockquote>On-device AI in Flutter promises offline features for free. Here’s what TFLite actually cost me in app size, battery life, and debugging time.</blockquote><p>A clinic nurse in Care Compass’s pilot program tried to pull up a patient triage suggestion and got a spinner. No signal, no fallback, just a loading wheel that never finished. That was the moment I stopped treating internet connectivity as a given in a Flutter app and started looking at TFLite for real.</p><p>Most Flutter apps treat AI as a network call. Ship a prompt to an API, wait for a response, render it. That works fine until the device carrying your app is in a rural clinic, a basement gym, or a subway car. I’d built exactly that pattern into Care Compass’s early triage flow, and it worked great in every demo, because every demo happened on office wifi. In production, with real users on real networks, it fell over constantly.</p><p>The fix wasn’t a better retry policy or a longer timeout. It was moving the model onto the device itself, so the app could produce a suggestion with zero network calls. TensorFlow Lite, <strong>TFLite</strong> for short, is the standard way to do that in Flutter through the tflite_flutter package. It’s also the point where “<em>add AI to the app</em>” turned into a real engineering project with costs I hadn’t priced in.</p><h4>The feature that only worked on good wifi</h4><p>Care Compass runs a triage assistant. A patient describes symptoms, the app classifies urgency, and a nurse decides who gets seen first. The first version called a hosted model over HTTPS. Simple, fast to build, easy to update because I could push a new model without touching the app binary.</p><p>It also meant the feature was useless anywhere the network was weak. Clinics in the pilot were in areas where signal came and went depending on the weather. A nurse who needed the triage suggestion in the first thirty seconds of a patient walking in didn’t have thirty seconds to spend on a retry loop. She closed the app and did it manually, which is exactly what the feature was supposed to prevent.</p><p>I could have added a longer timeout, a queue, an offline banner telling her to try again later. None of that fixes the actual problem. The actual problem is that the feature depends on something outside my control, and in this deployment, that thing failed often enough to make the feature untrustworthy. Untrustworthy features get ignored, and an ignored feature is worse than no feature at all because it still shows up in the UI, still gets tapped, and still fails.</p><h4>Why I picked TFLite instead of a smaller cloud fallback</h4><p>Before touching TFLite I looked at cheaper options first. A local rules engine instead of a model. A tiny cloud endpoint with aggressive caching. A hybrid where the app tries the network for two seconds and falls back to a cached last result.</p><p>None of them solved the real requirement, which was a fresh classification on a device with no connection at all. Caching gives you yesterday’s answer. A rules engine gives you a worse answer, because the whole reason we used a model was that symptom combinations don’t map cleanly to fixed rules. The only option that gave a correct, current answer without a network call was running the model on the device.</p><p>TFLite won over the alternatives, Core ML on iOS only, ONNX Runtime, a custom native inference layer, mostly because <a href="https://pub.dev/packages/tflite_flutter"><strong>tflite_flutter</strong></a> has a single Dart API that works on both platforms, and because TensorFlow already had our training pipeline. Converting an existing TensorFlow model to a .tflite file with post training quantization was a known, documented path. Writing a native inference layer for two platforms was not something I wanted to own alongside everything else Care Compass needed that quarter.</p><p>I also had to pick between int8 and float16 quantization before any of that mattered. Float16 kept accuracy almost identical to the full model but only shrank the file to around 28MB. Int8 got it down to 14MB and was noticeably faster on CPU, but cost close to two points of accuracy on our validation set, measured against symptom cases a clinician had already labeled by hand. Giving up accuracy for size on a health feature felt uncomfortable, so I kept a manual override in the flow: a nurse can always raise a suggested urgency level, never lower it automatically. That one decision did more for the pilot’s trust than any inference speed number.</p><p>That decision felt obvious at the time. What I didn’t have a good read on was what it would actually cost once it shipped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DLY4dlYop87ac6HVWDAf_Q.jpeg" /><figcaption>A tablet running a triage app on a clinic desk, the kind of setting where a stable connection is never guaranteed. Image generated via <a href="https://gemini.google.com/">Gemini</a></figcaption></figure><h4>What TFLite actually cost me</h4><p>Here’s the before and after, measured on the same release build, same test device, a mid range Android phone we used for QA.</p><p>Before, calling a hosted model over HTTPS:</p><ul><li>App size impact: close to zero. The model lived on a server, not in the binary.</li><li>Cold start: instant, no model to load.</li><li>Response time: 400 to 900 milliseconds depending on network quality, or infinite when there was no network at all.</li><li>Battery cost: a small radio wake per request, nothing meaningful.</li><li>Update path: push a new model to the server, no app release needed.</li></ul><p>After, running the quantized model with TFLite:</p><ul><li>App size impact: plus 40MB. That’s the int8 quantized model itself at around 14MB, plus the native TFLite binaries for both armeabi v7a and arm64 v8a architectures, plus the GPU delegate library I added later for faster inference.</li><li>Cold start: an added 180 to 260 milliseconds the first time the interpreter loads the model into memory per app session.</li><li>Response time: 40 to 90 milliseconds once the interpreter is warm, consistently, regardless of network.</li><li>Battery cost: measurable. Not dramatic, but running inference on a mid range CPU repeatedly through a shift adds up over a nurse’s full day of triage checks.</li><li>Update path: a full app release for every model update, since the model now ships inside the binary.</li></ul><p>The response time win is real and it’s the whole point. Forty to ninety milliseconds with zero dependency on signal beats a network call every time, including a fast one. But a 40MB size increase on a health app aimed at clinics with limited data plans is a real cost too, and it’s one I hadn’t weighed against the win until it was already in a release build.</p><pre>// Loading the interpreter once at app start, not per inference call.<br>// This is where the 180-260ms cold start cost shows up.<br>class TriageModel {<br>  late final Interpreter _interpreter;<br>  bool _isReady = false;<br><br>  Future&lt;void&gt; load() async {<br>    final options = InterpreterOptions()..threads = 2;<br><br>    // GPU delegate speeds up inference but adds another native<br>    // library to the APK, part of where the 40MB comes from.<br>    if (Platform.isAndroid) {<br>      options.addDelegate(GpuDelegateV2());<br>    }<br><br>    _interpreter = await Interpreter.fromAsset(<br>      &#39;assets/models/triage_v3_int8.tflite&#39;,<br>      options: options,<br>    );<br>    _isReady = true;<br>  }<br><br>  bool get isReady =&gt; _isReady;<br>}</pre><h4>The three debugging days nobody mentions in the tutorials</h4><p>The cost breakdown above is the part you can measure with a stopwatch and a build size report. The three debugging days were harder to see coming because each one looked like a different kind of bug until I traced it back to the same root cause: I’d underestimated what <em>“just run the model on device”</em> actually involves.</p><p>Day one went to a model that loaded fine and ran fine and returned confident, wrong answers. The quantized model expected input values normalized to a specific range, and the preprocessing code I’d copied from the server side pipeline normalized differently. Nothing crashed. It just quietly classified low urgency symptoms as high urgency, which is the worst kind of bug for a triage feature to have, because it fails silently and it fails in the direction that erodes trust the fastest.</p><p>Day two was jank, not incorrect output. My first working version ran interpreter.run() directly on the main isolate inside the widget’s build path. On the QA device, inference took close to 70 milliseconds, long enough to drop several frames every time a nurse tapped submit. The fix was moving inference off the UI isolate entirely.</p><pre>// Wrong: runs on the UI isolate, drops frames during inference.<br>Future&lt;TriageResult&gt; classifyBad(List&lt;double&gt; symptoms) async {<br>  final output = List.filled(1 * 4, 0.0).reshape([1, 4]);<br>  _interpreter.run(symptoms.reshape([1, symptoms.length]), output);<br>  return TriageResult.fromScores(output[0]);<br>}<br><br>// Fixed: hands the work to a background isolate through compute,<br>// keeping the interpreter call off the frame budget entirely.<br>Future&lt;TriageResult&gt; classify(List&lt;double&gt; symptoms) {<br>  return compute(_runInference, symptoms);<br>}<br><br>TriageResult _runInference(List&lt;double&gt; symptoms) {<br>  final output = List.filled(1 * 4, 0.0).reshape([1, 4]);<br>  _interpreter.run(symptoms.reshape([1, symptoms.length]), output);<br>  return TriageResult.fromScores(output[0]);<br>}</pre><p>Day three was iOS specific. The GPU delegate that worked cleanly on Android needed the Metal delegate on iOS, and getting that linked correctly through CocoaPods without breaking the existing Firebase pods in the same project took most of the day. None of this shows up in a five minute tflite_flutter quick start. It shows up when you’re shipping to two platforms with a real dependency graph already in place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NYgR4gWdkxf64CmgACUu2Q.jpeg" /><figcaption>Late night debugging session tracking down why on-device inference was dropping frames on a mid range test device. Image generated via <a href="https://gemini.google.com/">Gemini</a></figcaption></figure><h4>What I’d do differently</h4><p>None of this means TFLite was the wrong call. Care Compass needed a triage suggestion that worked with zero signal, and TFLite is the only option in the list that delivered that without a rewrite of the whole inference stack. But I’d plan the rollout differently if I were starting today.</p><p>The app size hit should have been a line item in the estimate, not a surprise QA found after the fact. Forty megabytes matters more on a health app aimed at low bandwidth regions than it would on a consumer app where users have unlimited data and fast wifi.</p><p>Moving inference off the main isolate needed to happen on the first commit, not after the jank showed up in testing. It is a five line change if you write it that way from the start, and a much bigger refactor once callbacks and state management are already wired around a synchronous call.</p><p>The preprocessing normalization should live in one place, shared between the training pipeline and the app, instead of getting hand ported twice with the two copies slowly drifting apart.</p><p>The model update path deserves to be treated as a real constraint too, decided on day one instead of discovered later. Shipping a new model now means a full app release, review time included, not a server side push. That changes how often you can realistically improve the model.</p><p>And I would have tested on the oldest device in our lab much earlier, not just the phone I carried around during day to day development. Inference time on that older device ran almost twice what I saw on my own phone, and that gap only surfaced once we ran a full device farm pass a week before launch. Later than I would have liked.</p><p>Takeaways, if you’re weighing this for your own Flutter app:</p><ul><li>TFLite buys you offline correctness and consistent latency, but it costs real app size, real battery, and a slower model update cycle.</li><li>Run inference off the main isolate from the start. Retrofitting that later is more work than doing it right the first time.</li><li>Match your normalization and preprocessing exactly between training and the on-device app. A silent mismatch produces confident wrong answers, not crashes.</li><li>Budget the platform specific work separately for Android and iOS. The GPU delegate setup is not the same on both, and it will not be a five minute task on either.</li><li>Decide upfront how often the model actually needs to update. If it’s frequently, on-device inference trades one problem for another.</li></ul><p>The triage feature works without signal now, and that was the actual requirement, not a nice to have. But “add on-device AI” turned out to be a much bigger project than “add a network call to a model,” and I priced it like the second one until the first release build told me otherwise.</p><p>If you’ve shipped TFLite or a similar on-device model in a Flutter app, I’d like to hear what your actual numbers looked like. Every write-up I found before doing this quoted inference speed and skipped the app size and battery cost entirely.</p><p>If posts like this are useful, I write about Flutter and mobile architecture most weeks.</p><p><strong>AUTHOR BIO</strong><br>Ali Wajdan is a Senior Mobile Engineer with 5+ years of experience shipping apps used by people across iOS and Android. I build cross-platform mobile apps, AI-integrated backends, and everything in between.</p><p>Portfolio: <a href="https://aliwajdan.com/">https://aliwajdan.com</a><br>LinkedIn: <a href="https://www.linkedin.com/in/aliwajdanpasha/">https://www.linkedin.com/in/aliwajdanpasha</a><br>GitHub: <a href="https://github.com/aliwajdan453">https://github.com/aliwajdan453</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d2f93feca76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Lines of Dart async* Code That Fixed My Infinite Scroll Pagination]]></title>
            <link>https://aliwajdan.medium.com/3-lines-of-dart-async-code-that-fixed-my-infinite-scroll-pagination-0485d392f567?source=rss-ce9f546e2aa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0485d392f567</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[pagination]]></category>
            <dc:creator><![CDATA[Ali Wajdan]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 10:01:02 GMT</pubDate>
            <atom:updated>2026-09-03T10:01:02.408Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ABvvUUL_9PX2ubb_owzsvA.jpeg" /><figcaption>A phone mid-scroll next to a laptop, standing in for the pagination logic running behind the list. Image generated via <a href="https://gemini.google.com/">Gemini</a></figcaption></figure><blockquote>Dart async* generators simplify Flutter pagination state. Here is the pattern I use instead of scattered page counters and duplicate fetch calls.</blockquote><p>I had a pagination bug that only showed up in production, never once locally. Users scrolling fast on a slow connection would trigger two fetches for the same page. My duplicate check code kept growing. Then I replaced the whole thing with a small Dart async* generator, and the bug disappeared along with about sixty lines of state tracking.</p><p>Most Flutter pagination code I have seen, including my own for years, wraps a mutable state object around a scroll listener. A page counter, a loading boolean, a hasMore flag, and a fetch method the UI calls when it hits the scroll threshold. It works until two scroll events fire close together, or a rebuild triggers a second load before the first future resolves. Then you are either debugging duplicate items in a list or writing defensive locks around a function that should not need them.</p><h4>Why manual pagination state breaks in Dart</h4><p>The failure mode is always the same shape. You check a loading flag, decide it is false, and start a fetch. But between that check and the moment you actually set the flag to true, the event loop has already let a second call through. It is a classic race condition, and it gets worse once the state lives across a page counter, a hasMore flag, and a loading flag that all need to stay in sync. Miss one update and you either fetch the same page twice or stop fetching entirely.</p><p>I patched around this for two years with debounce timers and manual locks. None of it addressed the actual problem, which was that pagination state had no single owner.</p><h4>Let the generator own the sequencing</h4><p>An async* function runs on one call stack. Every await inside it happens in order, so the function will not move past a yield until the previous fetch resolves. That gives pagination state one home instead of three scattered fields.</p><pre>Stream&lt;List&lt;Post&gt;&gt; fetchPostsPaginated(String query) async* {<br>  var page = 0;<br>  var hasMore = true;<br>  while (hasMore) {<br>    final batch = await api.fetchPosts(query, page: page);<br>    hasMore = batch.isNotEmpty;<br>    page++;<br>    yield batch;<br>  }<br>}<br><br>final iterator = StreamIterator(fetchPostsPaginated(query));<br><br>Future&lt;List&lt;Post&gt;&gt; loadNextPage() async {<br>  if (!await iterator.moveNext()) return const [];<br><br>  return iterator.current;<br>}</pre><p>The page counter and the hasMore flag now live inside the generator, scoped to that fetch lifecycle. There is nothing to forget to reset. When the search query changes, I do not touch three fields and hope I got them all. I just create a new generator and a new iterator.</p><p>I still guard the UI trigger with the one Future that loadNextPage returns. Most apps already disable the load more affordance while a request is pending, for the same reason a disabled button stops a double tap. That guard is the only piece of state I own now. Everything else, the ordering, the counting, the stopping condition, belongs to the generator.</p><p>Takeaways:</p><ul><li>In Dart, move pagination state, the page counter and hasMore flag, out of your widget or bloc and into the async* generator’s local scope.</li><li>Wrap the generator in a StreamIterator and let the UI pull one page at a time with moveNext, instead of pushing fetch calls from a scroll listener.</li><li>Keep exactly one guard, the pending future your load more trigger already awaits, instead of a page, hasMore, and loading trio spread across state.</li><li>Changing a search query or filter means creating a new generator, not carefully resetting three fields and hoping you got them all.</li></ul><p>This is not the only way to paginate in Flutter. Riverpod’s AsyncNotifier and various pagination packages solve the same problem with more structure and more code. For a straightforward paginated list, one async* function replaced a state class I had been patching for two years, and it has not needed a patch since.</p><p>Curious how others handle this. What patterns are you using?</p><p>If patterns like this are your thing, I post one or two of these a week.</p><p><strong>AUTHOR BIO</strong><br>Ali Wajdan is a Senior Mobile Engineer with 5+ years of experience shipping apps used by people across iOS and Android. I build cross-platform mobile apps, AI-integrated backends, and everything in between.</p><p>Portfolio: <a href="https://aliwajdan.com/">https://aliwajdan.com</a><br>LinkedIn: <a href="https://www.linkedin.com/in/aliwajdanpasha/">https://www.linkedin.com/in/aliwajdanpasha</a><br>GitHub: <a href="https://github.com/aliwajdan453">https://github.com/aliwajdan453</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0485d392f567" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Raised My RevenueCat Paywall Price 40%. Conversions Didn’t Drop]]></title>
            <link>https://aliwajdan.medium.com/i-raised-my-revenuecat-paywall-price-40-conversions-didnt-drop-7e8328c117f5?source=rss-ce9f546e2aa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e8328c117f5</guid>
            <category><![CDATA[revenuecat]]></category>
            <category><![CDATA[subscription]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ali Wajdan]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 10:01:03 GMT</pubDate>
            <atom:updated>2026-09-02T10:01:03.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_fLtyV1GjR9FHH17SUICRg.jpeg" /><figcaption>A phone paywall screen next to a laptop dashboard comparing two price variants during a live RevenueCat experiment. Image generated via <a href="https://gemini.google.com/">Gemini</a></figcaption></figure><blockquote>A RevenueCat paywall price experiment on a live subscription app, and what the conversion data actually showed after a 40 percent price hike.</blockquote><p>For eight months I kept my subscription price low because I was scared of a graph. Every time I opened the RevenueCat dashboard and looked at trial to paid conversion, I told myself that raising the price would tank it. Then a margin problem forced my hand, and the experiment I ran almost reluctantly taught me more about pricing than a year of guessing had.</p><p>This is the part most Flutter and mobile developers skip when they set up a RevenueCat paywall price experiment. They treat the launch price as sacred. It gets picked once, usually by scanning three competitor apps on the App Store, and then it sits untouched for a year while margins erode and nobody tests whether the number was ever right.</p><p>I had done exactly that with a subscription app I built on Flutter with RevenueCat handling entitlements. Launch price was 4.99 a month, chosen because two competitors charged 4.99 and one charged 5.99. No testing behind it. Just a guess dressed up as market research.</p><h4>The assumption that kept my price too low</h4><p>The assumption was simple and, in hindsight, lazy. I believed conversion rate and price moved in a straight line. Raise the price and conversion drops by roughly the same percentage. It felt intuitive enough that I never questioned it, and it gave me a convenient excuse not to touch pricing at all.</p><p>What actually kept the price frozen was fear of a support inbox full of cancellation emails and a conversion chart trending down on a dashboard I checked daily. Revenue per user was flat for months. Costs, especially AI inference costs for a couple of features, were not flat. At some point the math stopped working, and I had to either cut a feature or raise the price.</p><p>Cutting the feature felt like giving up on the thing users already liked. Raising the price felt like gambling with the only metric I obsessively tracked. So instead of guessing again, I ran a real experiment.</p><h4>Setting up the price experiment in RevenueCat</h4><p>RevenueCat has a paywall experiments feature that splits new users across two paywall variants tied to different underlying offerings, then reports trial conversion, paid conversion, and revenue per user for each group. You can test the price itself, not just the paywall design, while keeping the layout identical, which isolates the one variable that matters here.</p><p>I set up two offerings in the RevenueCat dashboard. The existing 4.99 monthly plan as the control, and a 6.99 monthly plan as the treatment, a 40 percent increase. Same paywall copy, same layout, same trial length. The only difference users saw was the number.</p><p>On the client side, the app just needed to render whatever offering RevenueCat assigned and tag every analytics event with the variant, so I could cross reference conversion data against my own retention numbers later, not just RevenueCat’s dashboard.</p><pre>Future&lt;void&gt; presentPaywallForUser() async {<br>  final offerings = await Purchases.getOfferings();<br>  final current = offerings.current;<br><br>  if (current == null) return;<br><br>  // RevenueCat assigns the experiment variant server side.<br>  // We just read whichever offering comes back and log it.<br>  final variantId = current.identifier;<br><br>  await analytics.logEvent(&#39;paywall_shown&#39;, parameters: {<br>    &#39;offering_id&#39;: variantId,<br>    &#39;price&#39;: current.availablePackages.first.storeProduct.priceString,<br>  });<br><br>  await RevenueCatUI.presentPaywall(offering: current);<br>}</pre><p>That single logged event, tying a user id to a variant id at the moment the paywall renders, ended up mattering more than the experiment dashboard itself. It let me join RevenueCat’s conversion numbers against my own Postgres tables weeks later, when I wanted to check churn by cohort instead of just day one conversion.</p><h4>What the data actually showed</h4><p>I expected conversion to drop by somewhere close to 40 percent, matching the price increase. That is what the straight line assumption predicted. It is not what happened.</p><p>Trial to paid conversion on the 6.99 variant dropped by about 3 percentage points compared to the 4.99 control, not 40. Revenue per trial started, RevenueCat’s blended metric that accounts for both conversion and price, went up by roughly 34 percent on the higher priced variant. The people who were going to convert at 4.99 mostly still converted at 6.99. Price was not the thing stopping the rest of them.</p><p>That result held once the sample crossed a few thousand trial starts per variant, which is roughly where RevenueCat’s own experiment guidance says the numbers stop being noise. Before that point the gap between variants bounced around enough that I would have made the wrong call if I had peeked early and shipped a decision off a week of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i-zm65vsZUcdqC_GLQafHQ.jpeg" /><figcaption>Comparing paywall conversion numbers between the two RevenueCat price variants side by side. Image generated via <a href="https://gemini.google.com/">Gemini</a></figcaption></figure><p>What surprised me more than the conversion numbers was where the drop landed. It was not evenly spread across the user base. Users who found the app through organic search, already looking for a specific solution, barely reacted to the price change. Users who arrived from a broad social post reacted more. They were browsing, not shopping, and a higher number gave them a reason to bounce that intent driven users never had.</p><h4>What I changed, and the part I am still watching</h4><p>I rolled the 6.99 price out to everyone. Revenue per new trial improved and stayed improved through the next full month, past the point where a novelty effect would have worn off.</p><p>The part I did not see coming until I checked a month later was refund and early cancellation behavior. A cohort query against my own database, joined with the RevenueCat webhook events I already store, showed the higher priced cohort canceling within the first billing cycle at a slightly higher rate than the control group did.</p><pre>select<br>  price_variant,<br>  count(*) filter (where cancelled_within_30_days) * 1.0 / count(*) as early_cancel_rate<br>from subscription_cohorts<br>where trial_started_at &gt;= &#39;2026-05-01&#39;<br>group by price_variant;</pre><p>The gap was small, about 1.5 percentage points, not enough to erase the revenue gain, but enough to tell me the higher price was pulling in some users whose expectations the app was not fully meeting. Price had shifted who converted, not just how many. That is the trade off nobody mentions when they talk about running a pricing test. A price increase that wins on revenue per user can still be quietly changing the makeup of your subscriber base in ways a conversion chart will not show you on its own.</p><p>I did not reverse the price. The revenue math was still clearly in favor of 6.99. But I did start tracking first cycle cancellation as its own metric, not just conversion, because that is the number that would have told me if I had gotten the price genuinely wrong instead of just differently right.</p><h4>Takeaways:</h4><ul><li>Test the actual price, not just paywall design, if margin is the real question</li><li>Wait for a real sample size before trusting an early lead in either direction</li><li>Conversion rate and price are not a straight line. Segment the drop by acquisition source before you draw conclusions</li><li>Revenue per trial started is a more honest metric than conversion rate alone</li><li>Watch early cancellation for a few billing cycles after any price change, not just day one conversion</li></ul><p>I went into this expecting to confirm my price was already too high. Instead I found out it had been too low for months, and the fear keeping it there was based on an assumption I had never tested. The RevenueCat paywall price experiment cost me a few weeks and a slightly awkward SQL query. Guessing had already cost me a year of margin.</p><p>If you have run a similar price test and seen the drop land somewhere else entirely, I would like to hear where.</p><p>If patterns like this are your thing, I post one or two of these a week.</p><p><strong>AUTHOR BIO</strong><br>Ali Wajdan is a Senior Mobile Engineer with 5+ years of experience shipping apps used by people across iOS and Android. I build cross-platform mobile apps, AI-integrated backends, and everything in between.</p><p>Portfolio: <a href="https://aliwajdan.com/">https://aliwajdan.com</a><br>LinkedIn: <a href="https://www.linkedin.com/in/aliwajdanpasha/">https://www.linkedin.com/in/aliwajdanpasha</a><br>GitHub: <a href="https://github.com/aliwajdan453">https://github.com/aliwajdan453</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e8328c117f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Node.js Docker Builds Took 6 Minutes. One Fix Cut It to 40 Seconds]]></title>
            <link>https://aliwajdan.medium.com/my-node-js-docker-builds-took-6-minutes-one-fix-cut-it-to-40-seconds-8d744b6715e0?source=rss-ce9f546e2aa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d744b6715e0</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Ali Wajdan]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 10:01:05 GMT</pubDate>
            <atom:updated>2026-09-01T10:01:05.173Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oWwOmMSlHIE1mhcwD1o7aA.jpeg" /><figcaption>A developer’s desk mid Docker build, terminal output and a Flutter app side by side. Image generated via <a href="https://gemini.google.com/">Gemini</a></figcaption></figure><blockquote>Dockerizing a Node.js backend for a Flutter app looks simple until the build times pile up. Here’s the layer order fix that actually worked.</blockquote><p>My CI pipeline used to sit at six minutes for a Docker build that touched exactly one line of application code. Six minutes for a change that didn’t touch a single dependency. I’d kick off a deploy, switch tabs, forget what I was doing, and come back to a green check that took longer than the code review did. That was the moment I stopped trusting my own Dockerfile.</p><p>The backend behind one of my Flutter apps runs on Node.js, and Docker was supposed to make that service trivially reproducible. Same image, same behavior, no more<em> “works on my machine”</em> arguments with myself at 11pm. What actually happened is I wrote a Dockerfile the way every tutorial writes one, shipped it, and didn’t look at it again until the build queue started backing up. By the time I did look, I had a container setup that rebuilt the entire dependency tree on every single commit, including commits that only changed a log statement.</p><h4>The Dockerfile that looked fine</h4><p>Here’s roughly what I started with. It runs, it produces a working image, and it is wrong in a way that only shows up once you’re deploying more than a couple of times a day.</p><pre>FROM node:18<br>WORKDIR /app<br>COPY . .<br>RUN npm install<br>EXPOSE 3000<br>CMD [&quot;node&quot;, &quot;server.js&quot;]</pre><p>Nothing here throws an error. The image builds, the container runs, tests pass locally. The problem is the order of two lines: COPY . . happens before RUN npm install. Docker builds images in layers, and it caches each layer based on whether the inputs to that step changed since the last build. COPY . . copies the entire project, including every source file. Change one file anywhere in the repo, and Docker treats that COPY layer as dirty. Every layer after it, including npm install, reruns from scratch. A one line change to a controller function was quietly forcing a full reinstall of every dependency, every time.</p><h4>Why this is the default, not the exception</h4><p>I didn’t write that Dockerfile carelessly. I wrote it the way almost every getting started guide writes it, because COPY . . followed by an install command is the easiest thing to explain in a tutorial. It works on the first build. It works on the second build too, if you’re just testing locally and not paying attention to how long each step takes. The failure mode only shows up under two conditions: you’re deploying frequently, and you actually look at your build timings instead of just waiting for the green checkmark.</p><p>Most Node.js backends for mobile apps don’t get built dozens of times a day early on, so nobody notices. Then the app grows, the backend takes on more routes, the dependency list grows with it, and suddenly every deploy is reinstalling a <strong>node_modules</strong> folder that didn’t need to change at all. I didn’t catch this because a build broke. I caught it because I got impatient waiting for a deploy that should have taken seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBR-0GO8F2Ua9RkrGCKZ4Q.jpeg" /><figcaption>Sketching out Docker layer order before rewriting the build. Image generated via <a href="https://gemini.google.com/">Gemini</a></figcaption></figure><h4>What I changed</h4><p>The fix isn’t clever. It’s ordering. Docker caches layers based on what changed, so the goal is to put the things that change least often earliest in the file, and the things that change most often last. Application source code changes constantly. Dependency lists change rarely. So the dependency install has to happen before the source code gets copied in, not after.</p><pre>FROM node:18-slim AS deps<br>WORKDIR /app<br>COPY package.json package-lock.json ./<br>RUN npm ci --omit=dev<br>FROM node:18-slim<br>WORKDIR /app<br>COPY --from=deps /app/node_modules ./node_modules<br>COPY . .<br>EXPOSE 3000<br>CMD [&quot;node&quot;, &quot;server.js&quot;]</pre><p>Two changes are doing the actual work here. First, only package.json and package-lock.json get copied before the install step, so that layer only invalidates when a dependency actually changes. Second, this is a multi stage build. The deps stage installs everything with npm ci, which is faster and more deterministic than npm install because it reads directly from the lockfile instead of resolving versions again. The final stage copies the installed node_modules over and then adds the source code, keeping the heavy, rarely changing install step cached across builds that only touch application logic.</p><p>The other piece that mattered almost as much was a .dockerignore file, which I genuinely hadn’t bothered with before this.</p><pre>node_modules<br>npm-debug.log<br>.git<br>.env<br>dist<br>coverage</pre><p>Without it, Docker was sending the entire project directory, including a stale local node_modules folder and my full git history, into the build context on every build. That context gets hashed and sent to the Docker daemon before the build even starts, so a bloated context slows things down before a single layer gets evaluated. Excluding node_modules alone shaved real time off that transfer, separate from anything the caching fix did.</p><p>The six minute build I opened with dropped to under a minute the first time I ran it after this change, and it settles around 40 seconds on a warm cache now. Cold builds, when the lockfile actually changes, still take close to the original time, because that’s real work Docker can’t skip. That part is expected. What changed is that the common case, a one line code change with no new dependencies, went from full reinstall every time to nearly instant.</p><h4>The trade-off nobody mentions</h4><p>Multi stage builds aren’t free. You now have two stages to reason about instead of one, and if you’re new to a Dockerfile like this, the COPY-from=deps line is not obvious at a glance. I’ve had to explain it to two different engineers who assumed node_modules was just showing up by magic. There’s also a discipline cost. Layer ordering only helps if you keep dependency changes isolated to package.json and package-lock.json, which means resisting the urge to drop a one off script or config file at the project root where it gets swept into that early COPY step and invalidates the cache anyway.</p><p>I still think it’s worth it. Once a Flutter app is in active development, the backend behind it gets redeployed several times a day, and that six minute tax adds up fast. The two stage Dockerfile is a cost you pay once, when you write it. The slow build is a cost you keep paying, commit after commit, until someone finally gets annoyed enough to fix it.</p><h4>Takeaways:</h4><ul><li>Layer order determines what Docker rebuilds. Copy dependency manifests before source code, not after.</li><li>COPY . . before an install step is the single most common Docker Node.js mistake, and most tutorials teach it that way.</li><li>A .dockerignore file cuts build context size before the build even starts. It’s not optional once your repo has real history and a local node_modules.</li><li>Multi stage builds separate the install step from the runtime image, which makes caching predictable and keeps the final image smaller.</li><li>Measure your build times before you assume Docker is doing its job. A working build isn’t the same as a fast one.</li></ul><p>I don’t think a slow Docker build is a crisis. It’s the kind of problem that’s easy to live with because nothing is actually broken. But I spent months treating six minutes as normal, and the fix took less time than one of those builds did.</p><p>If you’ve hit a different Docker gotcha with a Node.js backend, I’d like to hear what it was.</p><p>If patterns like this are your thing, I post one or two of these a week.</p><p><strong>AUTHOR BIO</strong><br>Ali Wajdan is a Senior Mobile Engineer with 5+ years of experience shipping apps used by people across iOS and Android. I build cross-platform mobile apps, AI-integrated backends, and everything in between.</p><p>Portfolio: <a href="https://aliwajdan.com/">https://aliwajdan.com</a><br>LinkedIn: <a href="https://www.linkedin.com/in/aliwajdanpasha/">https://www.linkedin.com/in/aliwajdanpasha</a><br>GitHub: <a href="https://github.com/aliwajdan453">https://github.com/aliwajdan453</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d744b6715e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Spent a Weekend Automating Flutter Screenshots. Fastlane Broke It Twice a Year]]></title>
            <link>https://aliwajdan.medium.com/i-spent-a-weekend-automating-flutter-screenshots-fastlane-broke-it-twice-a-year-926b5124ef53?source=rss-ce9f546e2aa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/926b5124ef53</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[fastlane]]></category>
            <dc:creator><![CDATA[Ali Wajdan]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 10:01:06 GMT</pubDate>
            <atom:updated>2026-08-31T10:01:06.323Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gX5MIs3UIfxOcMoamxU_Q.jpeg" /><figcaption>A Flutter developer’s desk mid build, the moment a screenshot automation run fails after an OS update. Image generated via <a href="https://gemini.google.com/">Gemini</a></figcaption></figure><blockquote>Automating Flutter App Store screenshots with Fastlane looked done after one weekend. Here is what broke every time Xcode shipped an update.</blockquote><p>I got the Fastlane screenshot pipeline working on a Saturday. By Sunday night it was generating a full set of App Store screenshots for every device size, in every locale, with zero manual steps. I closed my laptop feeling like I’d automated myself out of a chore for good.</p><p>Six weeks later, Apple shipped an Xcode update. The pipeline failed on the first run, not with a helpful error, but with a simulator boot timeout buried under forty lines of Ruby stack trace. I fixed it, moved on, and forgot about it until the next Xcode release did the same thing. That’s when it clicked: this wasn’t a one time bug. It was baked into how Fastlane’s snapshot tool works with Flutter apps.</p><h4>Why It Breaks Every Xcode Cycle</h4><p>Fastlane’s snapshot action for iOS was built for native Xcode UI testing. It drives a SnapshotHelper.swift file inside an XCUITest target, boots a matching simulator runtime, and steps through your app screen by screen. For a Flutter app, that UI test target is a thin shell around your Flutter code, but it still depends entirely on the simulator runtime that ships with your installed Xcode version.</p><p>Apple updates Xcode roughly twice a year, once around the fall OS release and once in spring with a smaller point update. Each time, the default simulator runtimes change. Sometimes older ones get dropped entirely. If your CI runner picks up the latest Xcode automatically, which most default GitHub Actions and Codemagic images do, your snapshot lane can quietly start booting a simulator that no longer matches the device profiles in your Snapfile. Your Flutter code did not change. The ground under it did.</p><pre># Fastfile, before: floating Xcode version<br>lane :screenshots do<br>  snapshot(<br>    devices: [&quot;iPhone 15 Pro&quot;, &quot;iPad Pro (12.9-inch)&quot;],<br>    languages: [&quot;en-US&quot;, &quot;es-ES&quot;]<br>  )<br>end</pre><p>Nothing in that lane pins a version. It trusts whatever Xcode the CI image has today, which is exactly the thing that changes without warning.</p><h4>What Finally Stuck</h4><p>The fix was not a smarter retry or a patched SnapshotHelper. I pinned the Xcode version explicitly in the lane, and I stopped letting CI upgrade it on its own schedule.</p><pre># Fastfile, after: pinned Xcode, explicit runtime<br>before_all do<br>  xcversion(version: &quot;16.1&quot;)<br>end<br><br>lane :screenshots do<br>  snapshot(<br>    devices: [&quot;iPhone 15 Pro&quot;, &quot;iPad Pro (12.9-inch)&quot;],<br>    languages: [&quot;en-US&quot;, &quot;es-ES&quot;]<br>  )<br>end</pre><p>Now an Xcode update only touches the pipeline when I decide to bump the pinned version, test it locally against the new simulator runtimes, and update the Snapfile if device names changed. It costs me twenty minutes, twice a year, on my schedule instead of a broken CI run on Apple’s.</p><p>The bigger lesson was about ownership, not Ruby syntax. Any tool that wraps a fast moving vendor SDK, Xcode, Android Studio, whatever comes next, needs a version boundary you control. Letting CI track latest felt convenient for exactly one weekend.</p><h4>Takeaways:</h4><ul><li>Fastlane’s snapshot action for Flutter apps depends on the Xcode simulator runtime, not just your app code.</li><li>CI images that auto update Xcode will break your screenshot lane on Apple’s schedule, not yours.</li><li>Pin the Xcode version explicitly with xcversion and bump it on purpose, twice a year.</li><li>Treat the Snapfile and device list as something to re-verify after every pinned version bump.</li><li>A pipeline that works once on your machine is not proof it will survive the next platform update.</li></ul><p>I still think automating App Store screenshots was worth the weekend. I just stopped trusting it to run unattended forever.</p><p>If you have found a cleaner way to decouple screenshot generation from the Xcode version entirely, I would like to hear it.</p><p>If patterns like this are your thing, I post one or two of these a week.</p><p><strong>AUTHOR BIO</strong><br>Ali Wajdan is a Senior Mobile Engineer with 5+ years of experience shipping apps used by people across iOS and Android. I build cross-platform mobile apps, AI-integrated backends, and everything in between.</p><p>Portfolio: <a href="https://aliwajdan.com/">https://aliwajdan.com</a><br>LinkedIn: <a href="https://www.linkedin.com/in/aliwajdanpasha/">https://www.linkedin.com/in/aliwajdanpasha</a><br>GitHub: <a href="https://github.com/aliwajdan453">https://github.com/aliwajdan453</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=926b5124ef53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Reused One Flutter Package Across Three Apps. Here’s Where the Abstraction Broke.]]></title>
            <link>https://aliwajdan.medium.com/i-reused-one-flutter-package-across-three-apps-heres-where-the-abstraction-broke-bc2e1f90825f?source=rss-ce9f546e2aa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc2e1f90825f</guid>
            <category><![CDATA[abstraction]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Ali Wajdan]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 10:01:04 GMT</pubDate>
            <atom:updated>2026-08-24T10:01:04.078Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ge0bWSbsgusEKw9-lcaJjA.jpeg" /><figcaption>Three phones, three apps, one shared Flutter package trying to serve all of them at once.</figcaption></figure><blockquote>A shared Flutter package held up fine across two apps until a Spanish fintech app joined. Here’s what broke, and how I restructured the package after.</blockquote><p>A caregiver using Care Compass got signed out mid save while logging a medication dose. The entry was lost, and she had to redo it from memory. The bug was not really in Care Compass. It lived in a shared Flutter package I had built two apps earlier, tuned for a fintech app that has nothing to do with medication logs.</p><p>I maintain one internal Flutter package that <a href="https://apps.apple.com/pk/app/dreamybot/id6743409461">DreamyBot</a>, <a href="https://apps.apple.com/pk/app/monetiza-copiloto-financiero/id6759417757">Monetiza</a>, and Care Compass all depend on. It handles design tokens, the network client, and the login flow. Three apps, three different sets of rules for what login and security are supposed to mean, one codebase making that decision for all of them.</p><p>Sharing code across apps looks like a free win on paper. Write the button once. Write the API client once. Write the login flow once. I believed that for about a year, and it mostly held up while DreamyBot and Care Compass were both low stakes apps with similar session models. Then Monetiza needed a security posture that had nothing in common with the other two, and the package I was proud of started fighting me instead of helping me.</p><h4>Why one shared package felt like the obvious call</h4><p>DreamyBot came first. It is an AI chat app, and building it meant writing a design system, an auth service wrapping Firebase, and a dio based API client from nothing. When Care Compass started a few months later, reusing that work instead of rebuilding it felt like the responsible call. Same buttons, same theme extensions, same AuthService class, same interceptors on the network layer. I pulled the whole thing into a private package and imported it into both apps through a single git dependency.</p><p>By the time Monetiza started, the package covered three things: a token based auth flow with refresh handling, a shared component library for buttons, inputs, and cards, and a network client with retry logic and logging baked in. Across three apps and a combined user base past 120,000, one change to a button style updated everywhere overnight. I remember being genuinely pleased with myself. Fixing a padding bug once instead of three times felt like the win I had been promised when I built the thing.</p><p>I was the only engineer touching all three apps at the time, which made the shared package feel even more sensible. One person, one mental model, one place to keep the rules consistent. I wired the package into each app’s CI pipeline through Codemagic so a version bump ran the full test suite for that app before merging, and for a while that was enough. The catch is that “<em>enough</em>” was measuring the wrong thing. The tests confirmed each app still built and passed its own checks. Nothing in that pipeline could tell me whether the assumptions baked into the shared code still matched what each app actually needed.</p><p>It worked well right up until the apps stopped being similar in the ways that mattered.</p><h4>Where auth broke first: Monetiza’s session policy</h4><p>DreamyBot’s auth is about as low stakes as auth gets. Email and password, or Apple sign in, a refresh token that lasts weeks, and a session that survives app restarts without asking the user to do anything. Care Compass started out close to the same model. Caregivers open the app several times a day, and forcing them to re-authenticate constantly would have made the app unusable.</p><p>Monetiza is different by design. It is a financial copilot for the Spanish market, and showing account balances or approving a transfer without a fresh biometric check was never going to pass review, let alone be a good idea. The compliance requirements I worked against wanted short session windows and a renewed biometric prompt before any screen that touched money.</p><p>My first fix was fast and wrong. I added a flag to the shared AuthService that branched on which app was calling it.</p><pre>class AuthService {<br>  Future&lt;Session&gt; refreshSession(String appId) async {<br>    if (appId == &#39;monetiza&#39;) {<br>      return _refreshWithBiometricCheck(<br>        maxAge: const Duration(minutes: 5),<br>        requireBiometric: true,<br>      );<br>    } else if (appId == &#39;care_compass&#39;) {<br>      return _refreshWithIdleLock(<br>        maxAge: const Duration(hours: 12),<br>        idleTimeout: const Duration(minutes: 15),<br>      );<br>    } else {<br>      return _refreshDefault(<br>        maxAge: const Duration(days: 14),<br>      );<br>    }<br>  }<br>}</pre><p>It shipped, it worked, and it was miserable to maintain. Every new app meant another branch. Every review of Monetiza’s session logic meant reading code that also controlled Care Compass and DreamyBot, hoping I had not broken a policy for a caregiver while patching a banking flow. That is exactly what happened. A change meant to tighten Monetiza’s idle timeout accidentally shortened Care Compass’s idle window too, because both branches read from a single shared idleTimeout field behind the scenes. That is the bug that opened this article. A caregiver got logged out mid save because a change built for a fintech app leaked into a health app through a method neither team had reason to look at.</p><p>I did not catch it right away. The crash reports were not crashes, just a spike in session refresh calls right after a Monetiza deploy, showing up in Care Compass’s Crashlytics dashboard of all places. It took me a day of comparing timestamps between the two apps’ release logs to notice the pattern lined up with a Monetiza release that had nothing to do with Care Compass on paper. Once I found the shared field, the fix took ten minutes. Finding it took a day, and that gap between cause and symptom is the actual cost of a shared abstraction that has quietly stopped fitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8D7F8gi-abR6AMvT1WKCkA.jpeg" /><figcaption>A late debugging session after a shared auth branch quietly changed session behavior across apps it was never meant to touch.</figcaption></figure><h4>Then the design tokens cracked too</h4><p>Auth was the loud failure. Design tokens were the slow one. Monetiza needed a calm, trustworthy palette and Spanish locale formatting, meaning comma decimal separators and euro symbols placed the way Spanish users expect, not the way an American fintech app would show them. Care Compass needed something else entirely: larger tap targets, higher contrast ratios, and support for text scaling well past what DreamyBot’s chat bubbles were ever designed to handle, because a meaningful share of Care Compass’s users are older adults with imperfect eyesight.</p><p>DreamyBot, meanwhile, is a playful app. Dark mode by default, expressive color, animated states. None of that belongs on a banking screen, and none of it should. A designer on the Monetiza side once flagged a build where the error toast used DreamyBot’s bouncy entrance animation on a failed transfer screen. Nobody had written that on purpose. It was the default animation curve from the shared component library, inherited because Monetiza’s own theme override never bothered to specify one, and nobody noticed until a real user watched their failed payment bounce onto the screen like a chat notification.</p><p>The shared ThemeData object grew the same way the AuthService did. A boolean here for high contrast mode, a locale check there for currency formatting, a conditional font scale override for Care Compass. Six months in, the file meant to keep the three apps visually consistent had become a place nobody wanted to touch, because nobody could predict which app a small edit would quietly affect.</p><p>The part that stung was realizing the two failures had the same shape. Auth broke because one file tried to encode three different security postures as branches. Design tokens broke because one file tried to encode three different visual languages as flags. Different domain, same root cause. I had built one abstraction and then kept asking it to represent things that were never actually the same thing twice.</p><h4>Before and after: splitting one package into three</h4><p>The actual fix took longer to accept than it took to build. I kept trying to patch the branching instead of admitting the branching itself was the problem. What finally worked was giving up on one package that tries to be correct for every app, and replacing it with a small core contract plus app specific implementations.</p><p>Before the split, every app pointed at the same git dependency, tracking the main branch directly.</p><pre>dependencies:<br>  shared_core:<br>    git:<br>      url: git@github.com:aliwajdan/shared-core.git<br>      ref: main</pre><p>That line is the real root cause of the caregiver bug, more than the branching logic itself. Every app always built against whatever was on main. A change written and tested against Monetiza went live in Care Compass’s next build the moment someone ran flutter pub get, whether or not Care Compass had ever been tested against it.</p><p><strong>The rebuild split the package into three:</strong> core_design, core_network, and core_auth, each with its own pubspec, its own changelog, and its own version number, managed together in one monorepo with melos so I can still test and publish all three from one place. core_auth now defines a contract instead of a policy.</p><pre>abstract class AuthStrategy {<br>  Duration get sessionMaxAge;<br>  bool get requiresRenewedBiometric;<br><br>  Future&lt;Session&gt; refresh(TokenPair tokens);<br>}<br><br>class MonetizaAuthStrategy implements AuthStrategy {<br>  @override<br>  Duration get sessionMaxAge =&gt; const Duration(minutes: 5);<br><br>  @override<br>  bool get requiresRenewedBiometric =&gt; true;<br><br>  @override<br>  Future&lt;Session&gt; refresh(TokenPair tokens) {<br>    return BiometricAuthenticator(tokens).refreshWithFreshCheck();<br>  }<br>}</pre><p>Each app now owns its own strategy class. A change to Monetiza’s session logic cannot touch Care Compass’s idle lock, because they are no longer branches inside the same function. They are separate classes in separate files that happen to implement the same interface.</p><p>The other half of the fix was treating the package like a real dependency instead of a shared folder. Each app now pins an exact version.</p><pre>dependencies:<br>  core_auth: ^2.3.0<br>  core_design: ^4.1.0<br>  core_network: ^1.8.2</pre><p>A breaking change to core_auth means a major version bump, and every app decides on its own schedule when to take it. Monetiza’s team can ship a stricter session policy the day it is ready. Care Compass does not inherit that change until someone deliberately bumps the version and runs the app’s own test suite against it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtNTyQAgPquCnN2XjeMNDQ.jpeg" /><figcaption>Sketching the split from one shared Flutter package into three independently versioned ones.</figcaption></figure><h4>What actually changed after the split</h4><p>This is not free. Three packages mean three changelogs, three version numbers to keep straight, and a CI pipeline that now builds and tests each one separately before any app can consume it. Onboarding a new contributor takes longer, because understanding semver discipline across three packages is a bigger ask than understanding one folder of shared widgets. The overhead did not disappear. It moved.</p><p>What it bought me is real, though. Six months since the split, a security change scoped to Monetiza has shipped four times without touching Care Compass’s build. Care Compass’s accessibility work can raise its minimum tap target size without anyone on Monetiza’s side even knowing it happened until they read a changelog. The class of bug that put a caregiver’s entry at risk, one app’s config leaking into another through a shared conditional, has not come back, because there is no longer a shared conditional for it to leak through.</p><p>I also added a small contract test suite that runs against every implementation of AuthStrategy, checking that each one returns a valid session shape and handles a failed refresh without throwing. It does not know or care whether the concrete class belongs to Monetiza or Care Compass. It only checks that whatever implements the interface actually honors it. That single test file has caught two regressions before they reached a release build, both times because a strategy implementation quietly stopped setting a field the interface required.</p><p>Melos ended up doing more work than I expected going in. Before, testing a change to the shared code meant using a local path override in each app’s pubspec, running the app manually, and hoping I remembered to switch every app back to the git dependency before committing. More than once I did not remember, and shipped a build pointing at a folder on my own machine. Melos lets me bootstrap all three packages and run their test suites in one command from the workspace root, and publish each one independently once its own tests pass. The apps still consume the packages the normal way, through pub, with a real version number attached. Nothing points at a local folder anymore unless I am actively working on it that day.</p><p>I still think one shared package for three apps was the right call at the start. DreamyBot and Care Compass genuinely looked alike for the first year. The mistake was not building the shared package. It was not noticing the moment the apps stopped being similar, and holding onto one version long after the apps needed different answers to the same question.</p><ul><li>A shared Flutter package works only as long as the apps consuming it actually agree on the rules. Branching inside one class the moment an app needs a different auth or design policy is a symptom, not a fix.</li><li>Watch for app specific conditionals creeping into a shared class. That is usually the first sign the abstraction has stopped matching reality.</li><li>Splitting a shared package by contract, not by app, keeps a change to one app’s auth or theme from silently reaching another app’s build.</li><li>Pin exact package versions per app instead of tracking a branch. It is the difference between a deliberate upgrade and an accidental one.</li><li>Overhead does not disappear when you split a package. It moves from debugging silent cross-app bugs to maintaining version discipline, and that trade is usually worth it once real users depend on the apps.</li></ul><p>I do not think there is a version of this story where I get the package structure right from day one. The three apps did not know yet how different they would become, and neither did I. What changed is how I watch for the signal now. The first app specific if statement inside a shared class is the moment to start planning the split, not six months and one production incident later.</p><p>If you have run a shared package across apps with genuinely different compliance requirements, I would like to hear where yours cracked first.</p><p>I write about Flutter architecture and the decisions that only show up after an app ships. Follow along if that is useful to you.</p><p><strong>AUTHOR BIO</strong><br>Ali Wajdan is a Senior Mobile Engineer with 5+ years of experience shipping apps used by people across iOS and Android. I build cross-platform mobile apps, AI-integrated backends, and everything in between.</p><p>Portfolio: <a href="https://aliwajdan.com/">https://aliwajdan.com</a><br>LinkedIn: <a href="https://www.linkedin.com/in/aliwajdanpasha/">https://www.linkedin.com/in/aliwajdanpasha</a><br>GitHub: <a href="https://github.com/aliwajdan453">https://github.com/aliwajdan453</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc2e1f90825f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Automated Flutter Release Notes. Half of Them Were Garbage.]]></title>
            <link>https://aliwajdan.medium.com/i-automated-flutter-release-notes-half-of-them-were-garbage-25ca14fdcda8?source=rss-ce9f546e2aa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/25ca14fdcda8</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Ali Wajdan]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 10:01:03 GMT</pubDate>
            <atom:updated>2026-08-22T10:01:03.543Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wf-bz3bRkp6pYGb-Jeztjg.jpeg" /><figcaption>A late release night, the terminal full of raw commit history next to the app the release notes were about to describe.</figcaption></figure><blockquote>Automated Flutter release notes from git commits looked efficient until the commit messages did not. Here’s the curation step that actually fixed it.</blockquote><p>The first automated release note I shipped to the Play Store read: fix bug in provider, wip, asdf, merge branch main into release. Four lines, three of which no user should ever see. A GitHub Actions job fired on tag push, Fastlane picked up the generated changelog, and by the time I noticed, the update was already sitting in the review queue waiting for Google to approve it.</p><p>I had wired automated changelog generation into a Flutter CI/CD pipeline built on Fastlane and GitHub Actions, expecting it to kill the fifteen minutes I spent every release writing App Store and Play Store notes by hand. Instead it turned raw commit history into something I now had to actively police. Most posts about release note automation assume the underlying git log is already clean: feat this, fix that, one line per meaningful change. My team’s commit history looked nothing like that, and if your team has more than two people committing to it, I would bet yours does not either.</p><h4>Why raw git commits make bad Flutter release notes</h4><p>A commit message is a note to your future self, or to a teammate reading a diff before a deploy. It was never written for someone scrolling a Play Store description and deciding whether to tap update. Mixing those two audiences is where the automation fell apart, and it took me a full release cycle to see it clearly.</p><p>My original setup was almost embarrassingly simple. On every tag push, a job grabbed everything between the previous tag and HEAD and handed it straight to Fastlane as the changelog.</p><pre>git log $(git describe --tags --abbrev=0 HEAD^)..HEAD --pretty=format:&quot;- %s&quot; &gt; release_notes.txt<br>fastlane deliver --changelog &quot;$(cat release_notes.txt)&quot;</pre><p>The script ran exactly as written, which was the problem. It printed every commit subject line verbatim: merge conflict resolutions, fixup commits from a rebase nobody squashed, one memorable please work from a Friday afternoon deploy. Individually harmless. Stacked into a changelog and pushed toward App Store Connect, the result read like an internal Slack thread. One of our beta testers actually asked what asdf meant in the update notes, and I did not have a good answer.</p><h4>The conventional commit fix that only got me halfway</h4><p>The obvious next move was Conventional Commits. Prefix everything with feat, fix, chore, refactor, and generate the changelog from categorized commits instead of raw ones. I got the team to agree to it in about ten minutes, which should have been my first warning that it would not stick.</p><p>That helped, briefly. Then hotfixes happened. Someone pushing a crash fix at eleven at night does not stop to think about commit taxonomy. They write fix crash and move on, and I do not blame them. Worse, the prefix only tells you what kind of change happened in the code, not whether a user should ever hear about it. A commit like feat: add debug flag to build config is a perfectly reasonable commit and a terrible release note. Conventional Commits solved the categorization problem. It did nothing for the audience problem, and it assumed a level of discipline that survives right up until the first deadline.</p><p>I also tried the tooling most guides recommend at this point: a commitlint check in CI that rejects any commit not matching the convention. It caught the format violations fine. It had nothing to say about a commit like fix: resolve issue, which passes every lint rule and still tells a user absolutely nothing. Linting checks the shape of a sentence, not whether the sentence means anything to someone outside the codebase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7DoE_N8fJBQyEAlw0PVZ3w.jpeg" /><figcaption>The two minute review step that quietly replaced fifteen minutes of manual release note writing.</figcaption></figure><h4>What actually fixed my Flutter release notes</h4><p>The fix that stuck was smaller than I expected, and it had three parts.</p><p>First, I stopped trying to enforce discipline on every commit and enforced it on exactly one message instead: the pull request title, which is the line that survives into the changelog on a squash merge anyway. A GitHub Actions check verifies that PR titles follow the feat or fix convention before the PR can merge. Nobody has to think about individual commit messages again, because individual commits stop mattering once the PR is squashed.</p><p>Second, the changelog generator only reads feat and fix prefixes. Everything else, chore, refactor, test, ci, gets filtered out before it ever reaches the release notes file. That single filter removed most of the internal noise, because most PRs were never user-facing changes to begin with.</p><p>Third, and this is the part that actually made the notes readable, I added a release note override. If a PR description contains a line starting with Release note:, the generator uses that line instead of the PR title. Writing one sentence for the rare feature that genuinely needs an explanation takes less time than writing a full changelog by hand, and it gives whoever shipped the feature control over how it reads to a user instead of leaving that to whatever they typed into the title box at six in the evening.</p><pre>for pr in &quot;${MERGED_PRS[@]}&quot;; do<br>  title=$(gh pr view &quot;$pr&quot; --json title -q .title)<br>  body=$(gh pr view &quot;$pr&quot; --json body -q .body)<br>  override=$(echo &quot;$body&quot; | grep -oP &#39;(?&lt;=Release note: ).*&#39;)<br><br>  if [[ -n &quot;$override&quot; ]]; then<br>    echo &quot;- $override&quot; &gt;&gt; release_notes.txt<br>  elif [[ &quot;$title&quot; =~ ^(feat|fix): ]]; then<br>    echo &quot;- $title&quot; &gt;&gt; release_notes.txt<br>  fi<br>done</pre><h4>The trade-off nobody mentions</h4><p>None of this made the process fully automated, and I stopped pretending it would. Fastlane still pulls the filtered, override-aware file straight into the release notes field for both stores, but nothing ships until someone reads it on the release pull request first. That review takes two or three minutes now instead of the fifteen I used to spend writing notes from scratch, so the automation is still a real win. It is just not the hands-off one I originally pictured.</p><p>The system also depends on the team actually following the PR title convention, and dependency bump PRs from automated tools still slip through the filter with titles like chore: bump package to 2.1.0. I still prune a line or two most releases, our dependency bot is relentless and does not read the PR template. If I add a contributor who has not seen the template yet, the whole thing quietly degrades back to manual editing until the habit sticks, usually after a release or two. Automation here bought me a draft, not a final answer. That is probably the ceiling for anything built on commit history instead of on actual intent, and I have made peace with it being lower than I hoped when I started.</p><ul><li>Commit messages describe what changed in the code, not what a user needs to know. Do not render them straight into a changelog.</li><li>Enforce message discipline on the PR title, not on every individual commit. It is the only message you actually control at merge time.</li><li>Filtering to feat and fix prefixes removes most internal noise without asking anyone to write anything extra.</li><li>A one-line release note override in the PR template covers the releases where a real sentence matters more than a category.</li><li>Keep a human review step before the changelog reaches the App Store or Play Store. Automated Flutter release notes should produce a draft, not a final answer.</li></ul><p>I still generate release notes automatically for every build. I just stopped expecting the git log to do a job it was never built for. The pipeline writes the first draft, the PR title convention keeps that draft honest, and I read it once before it goes anywhere near a store listing. That combination has held for months without a single garbage line reaching production, which is more than I could say for the version that piped git log straight into Fastlane and called it done.</p><p>If your team has cracked full automation without a review step, I would like to know how. I have not found a way to trust commit history that much yet.</p><p>I write about Flutter and CI/CD pipelines most weeks. Follow if that is useful.</p><p><strong>AUTHOR BIO</strong><br>Ali Wajdan is a Senior Mobile Engineer with 5+ years of experience shipping apps used by people across iOS and Android. I build cross-platform mobile apps, AI-integrated backends, and everything in between.</p><p>Portfolio: <a href="https://aliwajdan.com/">https://aliwajdan.com</a><br>LinkedIn: <a href="https://www.linkedin.com/in/aliwajdanpasha/">https://www.linkedin.com/in/aliwajdanpasha</a><br>GitHub: <a href="https://github.com/aliwajdan453">https://github.com/aliwajdan453</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25ca14fdcda8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Dart Filter Chain Looked Cached. It Was Rerunning Every Time.]]></title>
            <link>https://aliwajdan.medium.com/my-dart-filter-chain-looked-cached-it-was-rerunning-every-time-521f8cfd72e1?source=rss-ce9f546e2aa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/521f8cfd72e1</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Ali Wajdan]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 10:01:03 GMT</pubDate>
            <atom:updated>2026-08-21T10:01:03.061Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7NxobZbo3eWJf2-jlttYA.jpeg" /><figcaption>A phone scrolling through a notifications list next to the code that was quietly recomputing it on every frame.</figcaption></figure><blockquote>Dart Iterable chains stay lazy and never cache results. Here’s the pattern I use now, after years of rerunning the same chain twice per build.</blockquote><p>I spent two hours profiling a laggy screen before I found the real problem, and it had nothing to do with rendering. Three lines above my return statement sat a where then map chain, and every time something asked for its length, it reran against the full source list from scratch. Not cached. Not computed once. Rerun, every single call, for months, in a shipped app.</p><p>Dart’s Iterable is lazy by default. When you chain where, map, or expand, you are not building a new collection. You are building a recipe that only executes when something actually iterates it, a for loop, a length check, a toList call. Coming from languages where filter and map hand you back a materialized array immediately, that distinction is easy to miss. I missed it for close to two years, and I know I am not the only one, because the code that hides this bug looks completely correct.</p><p>I want to say I caught it because I am careful. I did not. A teammate mentioned the notifications screen felt choppy while scrolling, and I went looking for the wrong thing first, a heavy widget, an unnecessary rebuild higher up the tree. The Dart Iterable chain sitting in a getter was the last place I checked, mostly because getters feel like they should just return a value.</p><h4>The Dart Iterable chain that ran twice every frame</h4><p>Here is roughly what mine looked like. A getter that filters and transforms a list, called from inside build.</p><pre>class NotificationList extends StatelessWidget {<br>  const NotificationList({required this.allNotifications, super.key});<br><br>  final List&lt;NotificationItem&gt; allNotifications;<br><br>  Iterable&lt;NotificationItem&gt; get unreadNotifications =&gt;<br>      allNotifications.where((n) =&gt; !n.isRead).map((n) =&gt; n.withRelativeTime());<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      children: [<br>        Text(&#39;${unreadNotifications.length} unread&#39;),<br>        ...unreadNotifications.map((n) =&gt; NotificationTile(n)),<br>      ],<br>    );<br>  }<br>}</pre><p>Nothing here throws an error. Nothing warns you. But unreadNotifications is a getter, and it returns an Iterable, not a List. Every time you touch it, the where and map closures run again from the top of allNotifications. The Text widget triggers one full pass to get length. The spread just below it triggers a second full pass to build the tiles. Two passes per build, and build in Flutter can run dozens of times a second during a scroll or an animation. I had assumed the getter computed once and handed back a value. It does not. It hands back a promise to compute, and I was cashing that promise twice on every frame.</p><h4>Materialize once, at the point where you actually need the data</h4><p>The fix is one method call, placed deliberately instead of left implicit.</p><pre>class NotificationList extends StatelessWidget {<br>  const NotificationList({required this.allNotifications, super.key});<br><br>  final List&lt;NotificationItem&gt; allNotifications;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final unreadNotifications = allNotifications<br>        .where((n) =&gt; !n.isRead)<br>        .map((n) =&gt; n.withRelativeTime())<br>        .toList();<br><br>    return Column(<br>      children: [<br>        Text(&#39;${unreadNotifications.length} unread&#39;),<br>        ...unreadNotifications.map((n) =&gt; NotificationTile(n)),<br>      ],<br>    );<br>  }<br>}</pre><p>Calling toList() runs the chain exactly once and stores a concrete list. The length call and the second map now operate on that materialized list, which is cheap. The pipeline runs once per build instead of twice, and it stops silently re-walking the source array every time something touches the result.</p><p>The part I had to unlearn was treating laziness as a bug to route around everywhere. It is not. If you genuinely iterate a chain once, staying lazy saves you a full pass and the memory that pass would allocate. The mistake was calling the same lazy Iterable more than once and assuming Dart cached it for me between calls. It never did. The rule I use now is simple: the moment I plan to read the same Iterable chain a second time in one scope, I materialize it before the first read, not after.</p><ul><li>A Dart Iterable chain built from map, where, or expand does not cache anything. Every access reruns the full chain from the source list.</li><li>If you read a lazy Iterable more than once in the same function or build method, call toList() before the first read.</li><li>Getters that return Iterable are the easiest place to hide this bug, because the call site looks identical to a getter that returns an already-computed value.</li><li>Keep the lazy version when you only iterate once. Materializing something you touch a single time just spends memory for nothing.</li><li>Do not assume a getter is cheap just because it looks like one. Check what it chains before you call it twice in the same build.</li></ul><p>This one cost me more debugging time than I want to admit, mostly because the code read as correct at every step. Fixing it took one method call. Finding it took a teammate noticing something felt slow and me refusing to believe it was the obvious thing.</p><p>Have you run into a lazy Dart collection biting you somewhere unexpected? I would like to hear where it showed up.</p><p>If patterns like this are useful, I write about Flutter and Dart internals most weeks.</p><p><strong>AUTHOR BIO</strong><br>Ali Wajdan is a Senior Mobile Engineer with 5+ years of experience shipping apps used by people across iOS and Android. I build cross-platform mobile apps, AI-integrated backends, and everything in between.</p><p>Portfolio: <a href="https://aliwajdan.com/">https://aliwajdan.com</a><br>LinkedIn: <a href="https://www.linkedin.com/in/aliwajdanpasha/">https://www.linkedin.com/in/aliwajdanpasha</a><br>GitHub: <a href="https://github.com/aliwajdan453">https://github.com/aliwajdan453</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=521f8cfd72e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Flutter App Is Silently Showing Bad API Data in Production]]></title>
            <link>https://aliwajdan.medium.com/your-flutter-app-is-silently-showing-bad-api-data-in-production-2d5a94b3150e?source=rss-ce9f546e2aa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d5a94b3150e</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Ali Wajdan]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 10:01:03 GMT</pubDate>
            <atom:updated>2026-08-20T10:01:03.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5-YZXfkH-1s54dWM6U60A.jpeg" /><figcaption>A phone and a laptop showing the same appointment record telling two different stories.</figcaption></figure><blockquote>A Flutter app and its Node.js API drifted apart for weeks without a single crash. Here is the contract validation pattern I use now to catch it before release.</blockquote><p>Three weeks after a routine backend release, a user emailed asking why her appointment still showed as scheduled two days after she had cancelled it. I checked the database. Cancelled, no ambiguity there. I opened the app. Scheduled, sitting there like nothing happened. The API had been returning the right answer the whole time. My Flutter app had simply stopped understanding it.</p><p>That is the part that still bothers me. Nothing crashed. No red screen, no failed request, no alert in our logging tool. The response came back with a 200, valid JSON, correct field names. My app parsed it, found nothing it recognized as an error, and quietly fell back to a default value. It had been doing that for every appointment, for every user, for close to six weeks before anyone noticed.</p><h4>The Flutter bug that never threw an error</h4><p>Here is what happened on the backend. Appointment status used to be a single string field, one of scheduled, confirmed, cancelled, or completed. Simple enough that nobody thought twice about it. At some point the product wanted richer state: a reason code for cancellations, a rescheduled flag, a timestamp for the last change. So the backend wrapped it in an object. The old flat string stayed in the response during a transition period, then quietly disappeared once the mobile side confirmed the migration in a chat thread I was not part of.</p><p>My Dart model read the old field directly, something close to json appointmentStatus as a nullable string, falling back to scheduled if it was missing. When the field vanished, that fallback did exactly what I told it to do a year earlier. Every appointment in the app showed as scheduled until a user looked closely enough to notice her cancelled visit was still sitting on the calendar.</p><p>I have shipped a lot of code that fails loudly. This one didn’t. It just quietly told everyone a slightly wrong story about their own healthcare appointments, and it did it well enough that even our internal QA pass missed it, because the app never looked broken. It looked normal. That is worse.</p><h4>Why a JSON API drifts without anyone noticing</h4><p>This isn’t really a Flutter problem or a Node.js problem. It’s a boundary problem. Dart has a strong type system, but the moment you call jsonDecode on an HTTP response, that safety disappears. You get a Map of dynamic values, and everything after that is you asserting a shape you hope is still true. TypeScript on the Node.js side has the same gap. Types describe what the code intends to send, not what actually leaves the server after a hotfix, a partial rollout, or a field someone forgot to update in one branch of an if statement.</p><p>Most teams handle this with vibes. Someone posts in Slack that a field changed. Someone else updates the client, eventually. Manual testing clicks through the obvious screens and calls it done. That works right up until a change ships on a Friday, a transition period nobody flagged ends, or a field only shows up for a subset of users based on some backend condition the tester never triggered. None of that throws an exception. It just quietly produces the wrong screen for someone real, and the someone real is usually the one who tells you about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*564iGWF7nu5OtlwNjcdyXg.jpeg" /><figcaption>The schema file that now sits between the backend and the app, instead of a shared assumption.</figcaption></figure><h4>The contract I enforce between Flutter and Node.js now</h4><p>Every response shape that matters gets defined once, as a JSON schema, in a folder both the backend and the app treat as the source of truth. Not documentation nobody reads. A schema that things actually run against.</p><p>On the Node.js side, an integration test loads the schema and validates real response payloads against it before deploy. If a field gets renamed, removed, or its type changes without the schema being updated first, the build fails there, not three weeks later in a user’s inbox.</p><pre>{<br>  &quot;title&quot;: &quot;AppointmentResponse&quot;,<br>  &quot;type&quot;: &quot;object&quot;,<br>  &quot;required&quot;: [&quot;id&quot;, &quot;status&quot;],<br>  &quot;properties&quot;: {<br>    &quot;id&quot;: { &quot;type&quot;: &quot;string&quot; },<br>    &quot;status&quot;: {<br>      &quot;type&quot;: &quot;object&quot;,<br>      &quot;required&quot;: [&quot;state&quot;],<br>      &quot;properties&quot;: {<br>        &quot;state&quot;: {<br>          &quot;type&quot;: &quot;string&quot;,<br>          &quot;enum&quot;: [&quot;scheduled&quot;, &quot;confirmed&quot;, &quot;cancelled&quot;, &quot;completed&quot;, &quot;rescheduled&quot;]<br>        },<br>        &quot;reason&quot;: { &quot;type&quot;: [&quot;string&quot;, &quot;null&quot;] },<br>        &quot;updatedAt&quot;: { &quot;type&quot;: &quot;string&quot;, &quot;format&quot;: &quot;date-time&quot; }<br>      }<br>    }<br>  }<br>}</pre><p>On the Flutter side, the same schema gets pulled into a separate test suite, except instead of testing widgets it runs against a handful of recorded real API responses, fixtures captured from staging every time someone touches that endpoint. The test does not care whether my Dart model happens to parse the payload without throwing. It checks whether the payload still matches the contract both sides agreed to. A silent fallback like the one that broke appointment status would fail loudly here, in CI, before the release build even gets cut.</p><pre>const Ajv = require(&#39;ajv&#39;);<br>const schema = require(&#39;../contracts/appointment-response.schema.json&#39;);<br>const fixture = require(&#39;../fixtures/staging-appointment-response.json&#39;);<br><br>const ajv = new Ajv();<br>const validate = ajv.compile(schema);<br>const valid = validate(fixture);<br><br>if (!valid) {<br>  console.error(validate.errors);<br>  process.exit(1);<br>}</pre><p>That job runs on every pull request that touches the endpoint or the schema file, on both repos. It is not glamorous. It is a script that fails a build instead of a person finding out from a support message.</p><h4>What the contract costs you</h4><p>None of this is free. Someone has to own the schema file, and on a small team that someone is usually me. Every real change to an endpoint now means updating the schema first, which adds a step that a backend engineer moving fast will occasionally skip and get reminded about in review. Fixtures go stale if nobody refreshes them, and a stale fixture gives you false confidence, a green check that is testing yesterday’s API instead of today’s.</p><p>It also does not catch everything. The contract test verifies shape and type, not meaning. A backend change that keeps status as a valid enum value but quietly flips what it means downstream will sail right through validation and still confuse the app. A schema tells you the field is still a string. It has no opinion on whether cancelled means the same thing it meant last month.</p><p>I keep doing it anyway. The alternative is the six weeks I actually lived through, where a field quietly changed shape and not one person found out until a user did. A build failing on a pull request costs a few minutes. A user losing trust in whether the app tells them the truth costs a lot more than that.</p><h4>Takeaways:</h4><ul><li>A schema that both the Flutter app and the Node.js API validate against catches shape drift before it reaches a release build, not after a support ticket.</li><li>Null coalescing fallbacks like a default status value are exactly why a broken API response never throws an exception. Go audit yours.</li><li>Contract tests check shape, not meaning. Pair them with real monitoring, they are a floor, not a full safety net.</li><li>Refresh fixtures whenever the endpoint changes, or the test just validates data that no longer exists.</li><li>Decide who owns the contract file before the first drift happens, not after someone emails you about it.</li></ul><p>I don’t think schema validation is a glamorous fix. It won’t show up in a demo, and nobody claps for a CI job that quietly fails on a Tuesday afternoon. But it changed what kind of bug reaches my users. Renamed fields and type mismatches get caught in a pull request now, by a script, before a single person opens the app and sees the wrong thing. Whatever still reaches production is at least an interesting bug, one actually worth debugging instead of one that was just sitting there unnoticed.</p><p>If you have a different way of keeping a mobile client and its API honest with each other, I would genuinely like to hear it.</p><p>I write about Flutter and mobile architecture most weeks. Follow along if that’s useful to you.</p><p><strong>AUTHOR BIO</strong><br>Ali Wajdan is a Senior Mobile Engineer with 5+ years of experience shipping apps used by people across iOS and Android. I build cross-platform mobile apps, AI-integrated backends, and everything in between.</p><p>Portfolio: <a href="https://aliwajdan.com/">https://aliwajdan.com</a><br>LinkedIn: <a href="https://www.linkedin.com/in/aliwajdanpasha/">https://www.linkedin.com/in/aliwajdanpasha</a><br>GitHub: <a href="https://github.com/aliwajdan453">https://github.com/aliwajdan453</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d5a94b3150e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>