<?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 Mohamed Draz on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Draz on Medium]]></description>
        <link>https://medium.com/@mohamed.draz?source=rss-19decebcc3c0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cF4ET_5wMb_UyxQDaW-yXA.jpeg</url>
            <title>Stories by Mohamed Draz on Medium</title>
            <link>https://medium.com/@mohamed.draz?source=rss-19decebcc3c0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 13:05:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohamed.draz/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[BugCapsule: Give developers a bug they can run]]></title>
            <link>https://medium.com/@mohamed.draz/bugcapsule-give-developers-a-bug-they-can-run-07e66d97d08d?source=rss-19decebcc3c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/07e66d97d08d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Mohamed Draz]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 15:44:45 GMT</pubDate>
            <atom:updated>2026-10-26T15:44:45.020Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kVdybVg7os8xKuxvB1PVjQ.png" /></figure><p>Capture the context behind a failure, replay it against your code, and test the fix against the same recording.</p><p>QA sends you a video. Someone opens a screen, taps a button, and the app crashes. You follow the same steps. Everything works.</p><p>You check the app version, try another account, and ask what happened before the recording started. Before you can investigate the code, you have to reconstruct the conditions that made it fail.</p><p>A video shows what appeared on screen. The cause might depend on a response arriving before another request finishes, an old value in local storage, or server data your code did not expect. Repeating the same taps does not necessarily recreate the same situation.</p><p>BugCapsule records that context in a portable .bugcapsule file that developers can inspect and replay against the application.</p><p>Depending on the platform and integrations, a capsule can contain a storage checkpoint, user interactions, network requests and responses with their timing, application state, and the failure itself. Those details give the developer a concrete starting point for reproducing the problem.</p><p>Consider one of the bugs in the project’s Flutter demo: applying the SAVE100 coupon to a cart worth less than $100 produces a negative total. The application can keep running while displaying the wrong result.</p><p>To reproduce that bug, you need the cart data, the coupon entered, and the relevant server responses. You also need an assertion that defines the failure: the order total must never fall below zero. Without that condition, reaching the end of the checkout flow tells you very little about whether the calculation was correct.</p><p>A capsule preserves the recorded scenario. You can replay it against the code where the failure occurred, change the calculation, then test the change against the same recording.</p><p>That is what interests me about BugCapsule’s approach. Replay executes the application code using tools appropriate to each platform. On the web, Playwright drives the real application in Chromium. For Flutter, replay runs the app in a simulator or emulator environment and supplies recorded network responses through the supported integrations.</p><p>The team has a shared case to investigate. QA and development can examine the same recording instead of rebuilding the sequence from separate accounts of what happened.</p><p>Once the project and CLI are configured, the workflow looks like this. Replace &lt;id&gt; with the capsule’s identifier:</p><p>bugcapsule run &lt;id&gt; -n 3</p><p>After changing the code:</p><p>bugcapsule verify &lt;id&gt; -n 5</p><p>To keep the case as a regression test:</p><p>bugcapsule regress add &lt;id&gt;<br>bugcapsule regress run</p><p>The numbers specify how many attempts to request. They are not promised results. The verdict and execution details still matter.</p><p>A failure disappearing is not enough to establish that a fix worked. Replay might never reach the relevant action. It might encounter a request with no recorded response, or fail to restore part of the application state. Calling any of those outcomes a successful fix would give the developer false confidence.</p><p>BugCapsule distinguishes between verdicts such as FIXED, STILL FAILING, FLAKY, and INCONCLUSIVE. A clean attempt must replay all recorded inputs without a significant divergence. If one attempt succeeds and another cannot run, the result is inconclusive.</p><p>Even FIXED has a specific scope: the recorded scenario passed the verification criteria. It provides evidence about that case, rather than proof that the entire application is correct.</p><p>Keeping the capsule as a regression test extends its usefulness beyond the original ticket. The team can run it in CI and check whether a later change brings the failure back. The scenario that exposed the bug remains available after everyone has moved on to other work.</p><p>Getting there requires integration work. Connecting the SDK to your project establishes a connection; faithful replay also needs access to the network, navigation, and state involved in the failure. In Flutter, that means configuring the relevant integrations, such as Dio, GoRouter, and the supported state-management libraries.</p><p>There are limits. Flutter’s DateTime.now() and timers are not virtualized, so replay does not control every source of timing or nondeterminism. Web replay runs in Chromium, and paths such as service workers and third-party iframes fall outside the documented capture coverage. BugCapsule has SDKs for Flutter, Android, iOS, and the web, but their coverage is not identical.</p><p>I find those boundaries useful when evaluating the tool. They make the first experiment straightforward: choose an important application flow, connect the integrations it needs, and check whether its recording reproduces the failure consistently. If it does not, investigate what context is missing before relying on the result.</p><p>Recorded data deserves the same attention. Context that helps diagnose a bug may also contain information that should never leave the device. The SDK documents on-device redaction before storage or upload, along with controls for additional filtering and exclusions. Pattern-based redaction cannot identify every piece of personal information. Inspect actual capsules and tune the rules for your application’s data before expanding capture.</p><p>BugCapsule also includes error monitoring, release health, performance tracing, and user feedback. The connection I care about is the one between a reported failure and a recorded case that a developer can run, use to evaluate a change, and retain as a regression test.</p><p>Start with one bug that has been wasting your team’s time. Reproduce it before making a change, then verify the change against the same recording. That gives you something concrete to judge: whether the tool can preserve enough context to make this particular failure repeatable, and whether its verdict explains what happened.</p><p>The next time someone says, “I can’t reproduce it,” there is a file they can start with.</p><p>Explore BugCapsule: <a href="https://bugcapsule.com/">https://bugcapsule.com</a><br>Documentation: <a href="https://docs.bugcapsule.com/">https://docs.bugcapsule.com</a></p><p>Suggested Medium topics: Software Development, Debugging, Software Testing, Flutter, Developer Tools</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07e66d97d08d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Far Can You Push Dart? I Built a Neural Network to Find Out]]></title>
            <link>https://medium.com/@mohamed.draz/how-far-can-you-push-dart-i-built-a-neural-network-to-find-out-9158bdc71e88?source=rss-19decebcc3c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9158bdc71e88</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Mohamed Draz]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 10:46:13 GMT</pubDate>
            <atom:updated>2026-09-30T10:46:13.024Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7r3nI5Y7ydX5oDy6CzLOgA.png" /></figure><p>I’ve been learning AI in more depth lately, mostly out of curiosity. At some point, I wanted to take the math I was studying and implement it myself in Dart.</p><p>I wanted to see a model learn using code I could follow all the way down to the matrix multiplication. I also wanted to find out how Dart would handle the numerical work, and where its performance would start to fall behind.</p><p>So I built a small neural network from scratch, trained it, served it over HTTP, and then added experiments to test the things I thought might make it faster.</p><p>Some of those ideas worked. Switching to Float32 on its own actually made my implementation slightly slower.</p><p>The baseline uses pure Dart for all numerical operations, with no ML libraries, FFI, or native bindings. The only application dependencies are shelf and shelf_router for the HTTP server. I later added a separate FFI experiment to compare it with native BLAS.</p><p>The network is a small MLP:</p><p>2 → 64 → 64 → 3</p><p>It takes the x and y coordinates of a point and returns probabilities for three classes. I used a spiral dataset with 900 samples, split into 720 training samples and 180 test samples.</p><p>There are 4,547 trainable parameters. That kept the experiment small enough to inspect, while still giving the network a nonlinear classification problem to learn.</p><p>I started with a Matrix class backed by Float64List, storing values in row-major order. Then I implemented matrix multiplication, transpose, bias broadcasting, and the other operations needed by the network.</p><p>Each layer computes:</p><p>Z = A × W + b</p><p>The hidden layers apply ReLU. The output layer applies softmax.</p><p>For softmax, I subtract the maximum value in each row before applying the exponential. That keeps large finite logits from overflowing during exponentiation.</p><p>Training uses cross-entropy loss and mini-batch SGD. With softmax and cross-entropy, the gradient with respect to the logits simplifies to:</p><p>delta = (probabilities − one_hot_labels) / batch_size</p><p>Working backward through the network, the parameter gradients are:</p><p>dW = A_previousᵀ × delta</p><p>db = sumRows(delta)</p><p>To continue into the previous hidden layer:</p><p>delta_previous = (delta × Wᵀ) ⊙ ReLU′</p><p>One detail I paid attention to was when the weights change. I calculate every layer’s gradients before applying any updates. Otherwise, an earlier layer could receive a gradient calculated using weights that had already changed since the forward pass.</p><p>Writing that yourself makes the dependency pretty hard to miss.</p><p>A decreasing loss still wouldn’t prove that my implementation was correct, though. I wanted a more direct check.</p><p>I added a gradient check using central finite differences. For each parameter, I move its value slightly in both directions, measure the change in loss, and compare the numerical derivative with the gradient produced by backpropagation:</p><p>numerical_gradient ≈ (L(w + ε) − L(w − ε)) / (2ε)</p><p>On a small test network, the check covered all 54 parameters. The maximum relative error was about 2.9 × 10⁻⁹.</p><p>That gave me evidence that the backward pass matched the loss calculation at the tested parameter values. The baseline also has 47 tests covering matrix operations, model behavior, serialization, and reproducibility.</p><p>With a batch size of 32, a learning rate of 0.2, and 400 epochs, the baseline reached:</p><ul><li>Training accuracy: <strong>99.72%</strong></li><li>Test accuracy: <strong>98.89%</strong></li><li>Training time: approximately <strong>4.1 seconds</strong></li><li>Single-sample inference: approximately <strong>4.8 microseconds</strong></li></ul><p>The inference timing covers the model call, excluding HTTP handling.</p><p>These are results for a small synthetic dataset. The test set contains only 180 samples, so one or two predictions can noticeably change the reported accuracy. I wouldn’t use that percentage to make a broader claim about the model’s usefulness.</p><p>I also built the serving path. Training writes the model parameters to JSON, and the HTTP server loads them once and uses them for predictions. The numerical code stays separate from file access and HTTP handling.</p><p>That separation let me keep the baseline intact while adding follow-up experiments in an experiments/ directory.</p><p>I first compared the implementation with a NumPy version using the same architecture and training settings.</p><p>Single-sample inference was around 4.8 microseconds in Dart, compared with roughly 8.5 microseconds in NumPy. But NumPy trained about 7.6 times faster and handled a batch of 10,000 samples about 15 times faster.</p><p>The workload mattered a lot.</p><p>For a tiny forward pass, NumPy’s per-call overhead was significant relative to the arithmetic. As the amount of numerical work increased, its optimized backend pulled ahead.</p><p>There was also an important limitation in the comparison: using the same seed integers in Dart and NumPy doesn’t generate identical random values. The datasets, splits, and initial weights differed. The experiment compared similar workloads, rather than identical numerical inputs.</p><p>And my scalar Dart loops were running on one thread, while NumPy used Apple Accelerate’s optimized BLAS. I needed more experiments before attributing that gap to the language.</p><p>My first thought was to try Float32.</p><p>It halves the storage required per element compared with Float64, so I wanted to see whether reduced memory traffic would improve throughput.</p><p>In my scalar implementation, it didn’t. Under AOT, Float32 reached about 1.9 GFLOPS, compared with roughly 2.1 GFLOPS for Float64.</p><p>That was useful feedback: changing the storage type wasn’t enough to improve this loop.</p><p>Explicit SIMD made a much bigger difference.</p><p>Using Float32x4, the matrix multiplication kernel reached about 7.4 GFLOPS under AOT, roughly 3.5 times the Float64 scalar baseline.</p><p>There are trade-offs. Float32 reduces precision, and my kernel requires the output column count to be divisible by four. I also haven’t connected it to the MLP yet, so the 3.5× improvement is a kernel benchmark result. I haven’t measured the resulting training or inference improvement.</p><p>I tried Float64x2 as well. It gave roughly a 1.7× improvement and produced bit-identical results to the baseline in the tested cases.</p><p>I was also curious about loop order.</p><p>The baseline multiplication uses i-k-j order, which lets the inner loop read and write consecutive elements. I kept a conventional i-j-k implementation for comparison.</p><p>At smaller matrix sizes, especially under AOT, the difference was much smaller than I expected. Increasing the sizes made it clearer.</p><p>At 2048×2048, i-j-k dropped to around 0.50 GFLOPS, while i-k-j stayed near 2.16 GFLOPS. The difference was about 4.3×.</p><p>The optimization had a measurable benefit, but the small matrices in the original model didn’t expose much of it.</p><p>Next, I implemented Adam and compared it with SGD using the same data, initial weights, batch size, and shuffle seed.</p><p>I measured how long each optimizer took to reach particular loss thresholds. Evaluation time was excluded from those measurements.</p><p>With Adam’s learning rate set to 0.01, the epoch-average training loss reached 0.02 or below in about 185 milliseconds. SGD at a learning rate of 0.2 took about 1,260 milliseconds to reach that threshold.</p><p>That’s roughly a 6.8× difference for this target.</p><p>But Adam’s default learning rate of 0.001 wasn’t better on every measure. It reached some targets more slowly than SGD. Final test accuracy was also similar across the runs.</p><p>The optimizer and its learning rate needed to be considered together. Simply switching to Adam didn’t guarantee an improvement.</p><p>I also tried binary serialization.</p><p>The trained model occupied about 89.9 KB as JSON. Storing its parameters in a binary Float64 format reduced that to 35.6 KB, with bit-identical predictions after loading.</p><p>Binary Float32 reduced it further to 17.8 KB, with small changes in predicted probabilities.</p><p>For this tiny model, JSON loading was already fast enough that serialization wasn’t a pressing problem. The difference became more relevant when I tested a larger network with 669,706 parameters: JSON occupied about 13.6 MB, compared with 5.2 MB for binary Float64.</p><p>The experiment I found most interesting came last: calling BLAS from Dart through FFI.</p><p>I deliberately stepped outside the pure-Dart constraint for this separate benchmark and called Apple Accelerate’s cblas_dgemm.</p><p>I measured two paths. One copied ordinary Dart matrices into native memory and copied the result back. The other kept the buffers in native memory throughout the benchmark.</p><p>With native buffers, throughput reached roughly 330 to 350 GFLOPS at some of the larger sizes, close to the NumPy results on the same machine.</p><p>That helped explain the earlier comparison. A large part of the measured gap came from comparing my scalar implementation with an optimized numerical backend. Dart could call that backend too.</p><p>Buffer management mattered: copying data in and out reduced throughput, particularly at intermediate sizes.</p><p>The FFI version also came with practical costs. It currently runs only on macOS, manages native memory explicitly, and would need platform-specific work elsewhere. Those costs belong in the comparison alongside the speed.</p><p>There are still correctness details to improve in the project.</p><p>For example, very large finite inputs can pass input validation and overflow during the forward pass. Also, clamping probabilities before calculating the logarithm keeps the reported loss finite, but creates a mismatch with the gradient in extreme cases. Computing cross-entropy directly from logits using log-sum-exp would address that loss calculation more cleanly.</p><p>Those cases are a reminder of the limits of my current tests. Passing a gradient check at one set of values doesn’t establish numerical correctness everywhere.</p><p>All the performance measurements came from one machine, and it wasn’t completely idle. Small differences deserve caution. The experiments also measure different things: a faster matrix kernel, reaching a loss threshold sooner, and faster serialization are separate improvements.</p><p>What I enjoyed most was being able to connect the math to specific lines of code, then change the implementation and measure what happened. Float32 alone didn’t help. SIMD did. Loop order mattered more as the matrices grew. Calling the same kind of native backend used by NumPy changed the performance comparison substantially.</p><p>Next, I want to integrate the SIMD kernels into the MLP and measure training and inference end to end. After that, I want to reuse the model code inside Flutter and measure inference on a phone.</p><p>The code, tests, and benchmark results are on <a href="https://github.com/draz26648/dart_ml_lab">GitHub</a>. If you try the experiments on your own machine, I’d be interested to see your results.</p><p>You can also find me on <a href="https://www.linkedin.com/in/draz26648/">LinkedIn</a> if you want to talk about Dart, AI, or the implementation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9158bdc71e88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An OTP field that becomes its own loading animation in Flutter]]></title>
            <link>https://medium.com/@mohamed.draz/an-otp-field-that-becomes-its-own-loading-animation-in-flutter-c5523f034a8a?source=rss-19decebcc3c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5523f034a8a</guid>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <dc:creator><![CDATA[Mohamed Draz]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 20:35:59 GMT</pubDate>
            <atom:updated>2026-09-18T20:35:59.810Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*IJP2YcWfzv8F_uohZZfobA.gif" /></figure><p>I’ve published otp_animated_fields on <a href="https://pub.dev/packages/otp_animated_fields">pub.dev</a>. It&#39;s a Flutter package where the boxes you type your verification code into become the loading indicator.</p><p>Enter the last digit, and the boxes shrink and move into a circular orbit while the app checks the code. When verification succeeds, they collapse into a check mark. If it fails, they return to the row and shake.</p><p>My favorite part is the continuity. You can follow the same boxes through typing, waiting, and seeing the result.</p><p>The demo shows a four-digit code in a dark theme. After the user enters 1234, the boxes leave the row, orbit during verification, and come together into a green check mark.</p><p>Your app handles verification. The package handles the input and the animation around the result.</p><h3>Add it to your app</h3><p>Install the package with:</p><pre>flutter pub add otp_animated_fields</pre><p>The package requires Flutter 3.35 or newer and Dart 3.9 or newer.</p><p>For a basic integration, pass an async function to onVerify:</p><pre>import &#39;package:otp_animated_fields/otp_animated_fields.dart&#39;;</pre><pre>OtpAnimatedField(<br>  length: 4,<br>  autofocus: true,<br>  onVerify: (code) =&gt; authRepository.verifyOtp(code),<br>  onVerified: (code) {<br>    Navigator.of(context).pushReplacementNamed(&#39;/home&#39;);<br>  },<br>)</pre><p>In this example, authRepository.verifyOtp is your application&#39;s verification method. It should return a Future&lt;bool&gt;. The /home route also belongs to your app.</p><p>By default, entering the final digit submits the code. Return true to play the success animation or false to play the error animation.</p><p>After a failed attempt, the field clears the code and accepts another try. If you want users to edit the rejected code, set clearOnError: false.</p><p>There is a small detail here that matters when you connect navigation: onVerified runs after the success animation finishes. Navigating from that callback gives the check mark time to appear before the screen changes.</p><h3>Work with your existing verification flow</h3><p>You might already handle verification through Bloc or another state management setup. In that case, use OtpAnimatedController and leave onVerify out.</p><pre>final otp = OtpAnimatedController();</pre><pre>OtpAnimatedField(<br>  controller: otp,<br>  onCompleted: (code) =&gt; context.read&lt;OtpCubit&gt;().verify(code),<br>)</pre><p>Here, OtpCubit represents your application&#39;s existing verification logic. When it receives a result, call otp.succeed() or otp.fail() from your listener.</p><p>You can also submit through a button. Set autoVerify: false, then call otp.verify() when the user taps Verify.</p><p>If the code is incomplete, the field shakes and keeps the characters already entered. After your app handles a resend request, otp.reset() returns the field to an empty row.</p><p>Dispose of the controller when the widget that owns it is disposed.</p><h3>Adjust the timing and layout</h3><p>The package defaults to a minimum verification animation duration of 1.5 seconds. This keeps a fast response from making the loading state disappear almost immediately.</p><p>That is a visual choice, and it may not suit every screen. Set minimumVerifyingDuration: Duration.zero if you want the result animation to start as soon as possible.</p><p>The field also reserves enough vertical space for the orbit by default. Nearby content stays in place when verification starts.</p><p>If you prefer a more compact initial layout, set reserveOrbitSpace: false. The field will start at the row&#39;s height and grow as the boxes move into orbit.</p><p>Without an explicit theme, the field follows the surrounding Material theme. You can also start with a preset and change the details:</p><pre>OtpAnimatedField(<br>  onVerify: (code) =&gt; authRepository.verifyOtp(code),<br>  theme: OtpAnimatedTheme.dark(<br>    accentColor: const Color(0xFFFF5A3C),<br>  ).copyWith(<br>    boxSize: 64,<br>    borderRadius: 20,<br>    orbitPeriod: const Duration(seconds: 2),<br>  ),<br>)</pre><p>Color comes from Flutter; import package:flutter/material.dart or package:flutter/widgets.dart alongside the package import.</p><p>The theme lets you adjust spacing, text styles, glow, and other animation settings too.</p><h3>The input still needs to work</h3><p>The animation sits around a real Flutter text input. That input handles paste, backspace, and hardware keyboard input. It also supplies the oneTimeCode autofill hint for supported platform behavior.</p><p>The field supports text scaling and screen reader status announcements, with labels you can localize. It respects reduced motion preferences and keeps digits in left-to-right order within RTL layouts.</p><p>The example app includes a theme toggle and simulated verification. It accepts 1234 and rejects other codes, so you can try both outcomes before connecting your backend.</p><p>You can install <a href="https://pub.dev/packages/otp_animated_fields">otp_animated_fields from pub.dev</a> and find the source and example app on <a href="https://github.com/draz26648/otp_animated_fields">GitHub</a>.</p><p>If you try it in a verification screen, I’d be interested in how the animation timing feels in your app, especially when the verification request finishes quickly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5523f034a8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Skills That Made Claude Code Write Flutter I’d Actually Ship]]></title>
            <link>https://medium.com/@mohamed.draz/10-skills-that-made-claude-code-write-flutter-id-actually-ship-39a6acaf4b9d?source=rss-19decebcc3c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/39a6acaf4b9d</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[ai-skills]]></category>
            <dc:creator><![CDATA[Mohamed Draz]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 10:27:25 GMT</pubDate>
            <atom:updated>2026-08-03T10:27:25.222Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Every skill in this article is installable — repo and install commands at the end.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*noBylvvI5ksr3TGO6nFFaA.png" /></figure><p>Every Flutter developer who has tried building a screen with an AI agent knows the specific disappointment I’m describing.</p><p>You hand it a Figma frame. It gives you back four hundred lines that compile, render, and look roughly right in a screenshot. Then you open the file. EdgeInsets.all(16) in one widget, EdgeInsets.symmetric(horizontal: 16, vertical: 12) three widgets down, a hex color that exists nowhere in your theme, a SizedBox(height: 8) where your entire codebase uses a Gap. Nothing is broken. Everything is wrong.</p><p>You fix it. Next screen, same thing. You add a paragraph to your prompt about theme tokens. It works for that screen. Two days later, new session, no memory of the paragraph.</p><p>I spent longer than I want to admit treating this as a prompting problem. It isn’t. It’s a context problem, and the fix is structural.</p><h3>The thing prompting can’t solve</h3><p>An agent starts every session knowing Flutter in general and your codebase not at all. It has read a million repositories and will produce the statistical average of all of them, which is precisely what you don’t want.</p><p>The obvious workaround is CLAUDE.md. Put the conventions in a file, the file loads every session, done. Except the file grows. Mine got long enough that I noticed the agent skimming it — the architecture rules near the bottom quietly stopped being followed, because everything loaded at startup competes for attention with everything else. A CLAUDE.md that documents your entire engineering culture ends up documenting nothing.</p><p>Skills fix the loading problem. A skill is a folder with a SKILL.md inside, dropped into .claude/skills/ in your repo. Only the name and description load at startup. The body loads when the agent decides the skill is relevant. Fifty skills cost almost nothing until one is needed, at which point you get the full document instead of a bullet point that survived a summarization pass.</p><p>That’s the whole argument. Long, specific instructions become affordable.</p><p>I built ten, split across two plugins. Four keep the implementation matching the design; six cover architecture, robustness, and the pre-commit gate. The split exists because the first four are substantially more useful with the Figma MCP server connected and the second six need nothing at all.</p><p>Here’s what each one does and, more usefully, the specific failure it exists to prevent.</p><h3>The four that guard design fidelity</h3><h3>1. design-tokens</h3><p><strong>Prevents:</strong> hardcoded visual values that look identical to correct code in review.</p><p>One rule: no raw color, no numeric padding, no inline TextStyle in widget code. Everything resolves through a ThemeExtension.</p><pre>Container(<br>  padding: context.tokens.space.md,<br>  decoration: BoxDecoration(<br>    color: context.tokens.color.surfaceRaised,<br>    borderRadius: context.tokens.radius.card,<br>  ),<br>  child: Text(&#39;Balance&#39;, style: context.tokens.text.titleMedium),<br>)</pre><p>The rule that actually does the work isn’t the prohibition, though. It’s the instruction for what to do when a token is missing: <strong>add it to the token file first, then use it. Never inline a one-off.</strong> An agent without that rule will happily hardcode a value it couldn’t find, and one inlined value becomes five within a month.</p><p>There’s a second-order rule worth stealing. If the design uses a value that doesn’t fit the existing scale — 14px spacing where your scale is 4/8/12/16 — don’t add a space.s14 token. Stop and report it. It&#39;s nearly always a mistake in the design file, and silently encoding it makes the scale meaningless.</p><h3>2. figma-to-widget</h3><p><strong>Prevents:</strong> Stack and Positioned everywhere.</p><p>The default translation an agent produces reads pixel positions off the frame and reproduces them with absolute positioning. It matches the artboard exactly and breaks on every other screen size.</p><p>Figma’s layout system maps cleanly onto Flutter’s. The skill is mostly a table:</p><p>Figma Flutter Auto Layout, vertical Column Auto Layout gap spacing: or a Gap widget Hug contents MainAxisSize.min Fill container Expanded Absolute position Stack — last resort only Component variant a parameter, not a new widget</p><p>Two rules beyond the table matter. First, Stack is valid only when elements genuinely overlap — an avatar badge, a FAB over content. Overlap is the only justification. Second, check for an existing component before building a new one. A Figma component instance almost always corresponds to a widget that already exists in your codebase, and building a second PrimaryButton because the first wasn&#39;t found is the most common form of duplication in agent-generated UI.</p><h3>3. visual-verification</h3><p><strong>Prevents:</strong> treating the first render as the final one.</p><p>This is the one nobody builds and everybody needs. An agent with no feedback loop declares a screen finished the moment it compiles — it wrote code, the code ran, task complete.</p><p>The skill supplies the loop: build, screenshot through integration_test, diff against the exported frame, iterate until the difference falls under threshold. Capped at four iterations, because beyond that the remaining difference is usually something a diff can&#39;t fix — a missing font, a wrong export scale, a design updated after the export.</p><p>The diff logic lives in a Python script inside the skill folder rather than in the prose. This is the underused part of the skill system: <strong>scripts execute without consuming any context at all.</strong> Prose describing a comparison algorithm costs tokens on every single trigger and is less reliable than running the algorithm. Anything deterministic belongs in scripts/.</p><p>The skill also includes a short guide to reading a diff, which turned out to matter more than I expected:</p><ul><li>Sharp offset of the whole content block → a padding token is wrong</li><li>Text differing at the edges only → font weight, letter spacing, or line height</li><li>Everything shifted by a constant → export scale doesn’t match capture device pixel ratio; fix the export, not the code</li><li>Text differing in shape entirely → the font isn’t bundled; check pubspec.yaml before touching the widget</li></ul><p>Without that guide the agent will “fix” a font-loading problem by adjusting padding until the numbers improve.</p><h3>4. golden-tests</h3><p><strong>Prevents:</strong> drift after the match.</p><p>Visual verification proves a screen matches today. Goldens stop it drifting tomorrow.</p><p>The skill covers the test matrix — small phone, large phone, tablet, light and dark, text scale 1.0 and 2.0, LTR and RTL — with a note that the full cross-product is too many images for anyone to review. Cover the baseline on every device, then one variant each for dark, large text, and RTL.</p><p>The rule I’d single out: <strong>never run </strong><strong>--update-goldens as a reflex when a test fails.</strong> That command always makes the test pass, which means a failing golden is only useful if someone looks at what changed. Regenerate only after confirming the change was intended, then open the changed PNGs and actually look at them. If a golden changed and nobody can say why, that&#39;s a bug being committed, not a test being updated.</p><p>Tokens stop drift at authoring time, verification catches it at build time, goldens prevent it from coming back. Each covers a gap the other two leave open.</p><h3>The six that guard the code</h3><h3>5. architecture</h3><p><strong>Prevents:</strong> files landing in the wrong layer, which is far more expensive to fix later than to get right now.</p><p>Feature-first, three layers per feature, dependencies pointing inward. The rule with the most practical bite: <strong>domain imports nothing from Flutter.</strong> Not material.dart, not even for Color. The moment domain depends on Flutter it needs a binding to test, and unit tests go from milliseconds to seconds.</p><p>The skill also includes a “where does this go” table, which resolves more arguments than the folder diagram does:</p><p>Thing Layer “Transfer requires balance ≥ amount” domain/usecases “Balance shows two decimals” presentation “The API returns cents as an int” data/models “Failed transfers retry twice” data/repositories</p><p>And an explicit permission to skip ceremony: a use case that only forwards a call to a repository adds a file and no behaviour. Let the Cubit call the repository directly for straight reads. Agents love generating full Clean Architecture ceremony for a settings toggle, and a skill that only says “follow the layers” encourages it.</p><h3>6. state-management</h3><p><strong>Prevents:</strong> intermittent crashes and unnecessary rebuilds.</p><p>Sealed states via freezed, so adding a state member produces a compile error everywhere it needs handling rather than a silently missing case at runtime.</p><p>The rule that catches a real production bug:</p><pre>Future&lt;void&gt; load() async {<br>  emit(const WalletState.loading());<br>  final result = await _repository.fetchWallet();<br>  if (isClosed) return;   // &lt;- this line<br>  ...<br>}</pre><p>Without that guard, navigating away mid-request throws. It’s intermittent, depends on network timing, and is very hard to reproduce from a bug report. An agent will not add it unless told to.</p><p>The rebuild rule: BlocBuilder rebuilds on every state change, so when a widget needs one field, use BlocSelector. On a screen where a header and a list read the same Cubit, a plain BlocBuilder on the header rebuilds it on every list update. Not fatal, but it accumulates, and it&#39;s free to avoid.</p><h3>7. responsive-adaptive</h3><p><strong>Prevents:</strong> code written to the artboard width.</p><p>A design file gives you one width. The app runs on hundreds.</p><p>The distinction the skill makes that I don’t see stated often enough: LayoutBuilder for how a component lays <em>itself</em> out, MediaQuery for screen-level decisions like navigation pattern. A card in a 400pt sidebar on a 1200pt screen should lay out as a narrow card — MediaQuery would report a wide screen and be wrong.</p><p>Also worth knowing: use MediaQuery.sizeOf(context) rather than MediaQuery.of(context).size. The latter subscribes the widget to every MediaQuery change including keyboard appearance, which means rebuilds on every keystroke.</p><p>And a rule that sounds paranoid until it saves you: scroll by default. Any screen with more than three elements can overflow once text scale is raised.</p><h3>8. a11y-and-rtl</h3><p><strong>Prevents:</strong> the entire category of requirement your design file will never mention.</p><p>I build for Arabic-speaking markets. Every Figma file I have ever received was laid out left to right, at a fixed artboard width, at default text scale, in one language. Every one.</p><p>This isn’t a criticism of designers. It’s a category that lives entirely on the implementer’s side, which makes it exactly what gets skipped under deadline and discovered by users.</p><p>EdgeInsets.only(left: 16) puts padding on the left in every language. In Arabic the layout mirrors and the padding doesn&#39;t, which looks subtly broken in a way that&#39;s hard to name and easy to notice. EdgeInsetsDirectional, AlignmentDirectional, PositionedDirectional — start and end, never left and right.</p><p>The part that needs actual judgement is icon mirroring, so the skill carries a table:</p><p>Mirrors Doesn’t mirror Back and forward arrows Play and pause Navigation chevrons Clock faces Send Checkmarks Undo and redo Logos and brand marks</p><p>Then text scaling, which is the most common Flutter accessibility failure and entirely preventable: no fixed heights on containers holding text, no maxLines: 1 with ellipsis on content the user needs to read, buttons that grow with their label. And explicitly: <strong>never clamp the scale factor globally to protect the layout.</strong> That overrides a setting the user deliberately chose, and on iOS it&#39;s grounds for review rejection.</p><p>Plus semantics labels on icon-only buttons, ExcludeSemantics on decorative images, 48dp minimum touch targets, and no hardcoded strings — including semantics labels, which are read aloud and therefore read in the wrong language if untranslated.</p><p>It’s a short list and it never gets done consistently by hand.</p><h3>9. performance</h3><p><strong>Prevents:</strong> the fixes that are nearly free at authoring time and expensive to retrofit.</p><p>The structural rule with the largest impact: <strong>extract widgets rather than helper methods.</strong> A Widget _buildHeader() rebuilds with its parent every time. A separate const HeaderWidget() does not.</p><p>The one that prevents crashes: always set cacheWidth on network images. Without it a 2000px image decodes at full size to fill a 100px avatar, holding roughly 16MB for something that needs 40KB. On a scrolling list of avatars that&#39;s the difference between a smooth list and an OOM crash on a mid-range Android device.</p><p>And a caution about RepaintBoundary, because agents will otherwise scatter them everywhere: each boundary is a separate layer with real memory cost. Add them where the repaint rainbow shows something flashing that shouldn&#39;t be, not preemptively.</p><h3>10. review-gate</h3><p><strong>Prevents:</strong> the gate satisfying itself.</p><p>Formatting, static analysis with --fatal-infos, forbidden pattern grep, tests, coverage. Standard stuff. One design decision makes it worth including:</p><pre>allowed-tools: Read, Grep, Glob, Bash</pre><p>No write access. A quality gate that can edit code will eventually satisfy its own checks by deleting the assertion that failed. Restricting the tools makes that structurally impossible rather than relying on it behaving well.</p><p>The skill reports in three groups — blocking, worth fixing, notes — and includes one instruction that matters: if nothing is blocking, say so plainly rather than manufacturing findings to look thorough. A gate that always reports problems teaches people to ignore it.</p><h3>What doesn’t work</h3><p>I’d rather be useful than promotional.</p><p><strong>Skills undertrigger.</strong> This is the failure mode, not overtriggering. The description field is the only text loaded at startup and it&#39;s the entire basis for whether the skill opens. Write it as trigger conditions, not a summary, and lean pushy — name specific phrases and situations, including cases where you wouldn&#39;t think to ask for the skill by name. I wrote most of my first drafts too politely and they simply never fired.</p><p><strong>The Figma MCP server needs a paid Dev or Full seat.</strong> Without it the agent is reading a rasterized screenshot and guessing at values, and no skill fixes guessing. Real cost, worth knowing before you plan around it.</p><p><strong>Skills don’t fix a bad design file.</strong> If your Figma has no variables, no consistent spacing scale, and forty-three shades of grey, a design-tokens skill will faithfully encode the chaos.</p><p><strong>A skill library is maintenance.</strong> Ten skills is ten documents that go stale when your architecture changes. Committing them to the repo helps — they show up in pull requests like any other code and get reviewed — but it’s ongoing work, not a one-time setup.</p><p><strong>Skills conflict with each other if you’re careless.</strong> My performance skill wanted const constructors everywhere; my design-tokens skill routes values through context.tokens, which isn&#39;t const-constructible. Both were right in isolation and the agent oscillated between them until I resolved it explicitly in the tokens skill. Expect to find a few of these.</p><h3>Where to start</h3><p>Don’t build ten. Build one.</p><p>Write design-tokens this week, specific to your actual theme file rather than to generic Flutter, and use it for a few days. Every place the agent does something you didn&#39;t want is a rule your skill is missing. That friction is the specification — it tells you what to write next far more reliably than sitting down to imagine every rule in advance.</p><p>The mental shift that made this click for me was giving up on the idea of a perfect prompt. There isn’t one. What there is, is the accumulated set of decisions your team already made about how code should look, currently living in the heads of three senior developers and nowhere else.</p><p>Skills are just the first time it’s been worth writing them down.</p><h3>Get them</h3><p>The repo is a Claude Code plugin marketplace, so it’s three commands:</p><pre>/plugin marketplace add draz26648/flutter_claude_skills<br>/plugin install flutter-design-fidelity@draz-flutter<br>/plugin install flutter-code-quality@draz-flutter</pre><p>github.com/draz26648/flutter_claude_skills — MIT, and the README explains what each skill enforces in more detail than fits here.</p><p>One caveat worth stating plainly. These encode one specific set of conventions: freezed, Cubit, feature-first, an AppTokens extension. If yours differ, the skills will fight your codebase, and the skill loses. Fork and adapt rather than installing and hoping — the README has a prompt that gets Claude to read your project and rewrite the skills to match what&#39;s actually there. The structure is the reusable part. The specifics aren&#39;t.</p><p><em>If these skills save you even a fraction of the review time they’ve saved me, they’re worth trying. And if they don’t fit your codebase, fork them, rewrite them, and make them yours. That’s the whole point.<br>Follow me here : <br></em><a href="https://github.com/draz26648"><em>Github</em></a><em><br></em><a href="https://www.linkedin.com/in/draz26648/"><em>LinkedIn</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39a6acaf4b9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Security in Production: What Senior Devs Actually Do]]></title>
            <link>https://medium.com/@mohamed.draz/flutter-security-in-production-what-senior-devs-actually-do-ecaf8fef93af?source=rss-19decebcc3c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecaf8fef93af</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[mobile-app-security]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Mohamed Draz]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 07:36:03 GMT</pubDate>
            <atom:updated>2026-06-25T07:36:03.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KzUjv3wjlDr2ozZSq04BFg.png" /></figure><p><em>A no-BS deep dive into every layer of defense that actually matters — secrets management, SSL pinning, token vaults, runtime integrity, encrypted storage, and API hardening.</em></p><p>Most Flutter security articles stop at flutter_secure_storage. Drop a key in the keychain, call it a day.</p><p>That’s not security. That’s a checkbox.</p><p>After shipping Flutter apps across fintech, health, and e-commerce — domains where a single breach can end a company — I’ve built up a layered defense model that I actually use in production. This article covers all seven layers: secrets, network, auth, obfuscation, runtime integrity, local storage, and API hardening.</p><p>No beginner hand-holding. Let’s go deep.</p><h3>The Mental Model First</h3><p>Before the code, the architecture:</p><pre>[Transport:  TLS + Certificate Pinning        ]<br>  [Identity: JWT in memory, refresh in enclave]<br>    [Runtime: Jailbreak / root / debugger     ]<br>      [Storage: SQLCipher + AES-GCM fields    ]<br>        [API:   HMAC signing + replay defense ]<br>          [Binary: Obfuscation + symbol strip ]</pre><p>Each ring assumes the previous one <em>can</em> fail. A bypassed SSL pin shouldn’t expose raw secrets. A rooted device shouldn’t expose the database. A leaked token shouldn’t expose long-term credentials.</p><p>Defense in depth isn’t paranoia — it’s the only architecture that holds when an attacker is more patient than you expect.</p><h3>1. Secrets Management: Stop Lying to Yourself About .env</h3><p>The first sin of Flutter security: storing secrets in dart-define, .env files, or hardcoded strings.</p><pre>// ❌ Strings are trivially extractable from the binary<br>const apiKey = &#39;sk-prod-abc123&#39;;</pre><p>dart-define values are compiled into the AOT binary. Any attacker with strings or a Dart decompiler has them in minutes. This isn&#39;t theoretical — it&#39;s a ten-minute exercise.</p><p><strong>The right architecture:</strong> secrets that never touch the client. Your API keys, signing secrets, and third-party credentials live on your backend. The app authenticates the <em>user</em>, the backend authenticates <em>itself</em> to third-party services. Full stop.</p><p>For secrets the app genuinely needs at runtime — like encryption keys — derive them from user credentials instead of storing them:</p><pre>import &#39;package:pointycastle/export.dart&#39;;</pre><pre>// ✅ PBKDF2 key derivation — the raw secret never exists anywhere<br>Uint8List deriveKey(String password, Uint8List salt) {<br>  final params = Pbkdf2Parameters(salt, 100000, 32); // 100k iterations<br>  final pbkdf2 = KeyDerivator(&#39;SHA-256/HMAC/PBKDF2&#39;)..init(params);<br>  return pbkdf2.process(Uint8List.fromList(utf8.encode(password)));<br>}</pre><p>100,000 iterations makes brute-forcing the derivation expensive. The key lives in memory only while it’s needed, derived fresh from the user’s credential each session. Nothing is stored.</p><p>For session-persistent secrets, use the platform’s secure enclave — with the right options:</p><pre>// ✅ flutter_secure_storage with hardened platform options<br>const storage = FlutterSecureStorage(<br>  aOptions: AndroidOptions(<br>    encryptedSharedPreferences: true,<br>    keyCipherAlgorithm: KeyCipherAlgorithm.RSA_ECB_OAEPwithSHA_256andMGF1Padding,<br>    storageCipherAlgorithm: StorageCipherAlgorithm.AES_GCM_NoPadding,<br>  ),<br>  iOptions: IOSOptions(<br>    accessibility: KeychainAccessibility.first_unlock_this_device,<br>    synchronizable: false, // ← most devs miss this<br>  ),<br>);</pre><p>synchronizable: false is the option most developers miss. You don&#39;t want encryption keys syncing to iCloud Backup, where they&#39;re outside your security perimeter entirely.</p><h3>2. Network Security: SSL Pinning That Actually Holds</h3><p>TLS is table stakes. Certificate pinning is the actual defense — it prevents interception even if a trusted CA is compromised or a corporate proxy is in the path.</p><p><strong>The wrong way:</strong> pin the leaf certificate. It breaks on every cert rotation, which means you either ship emergency updates or disable pinning under pressure.</p><p><strong>The right way:</strong> pin the SHA-256 hash of the SubjectPublicKeyInfo (SPKI) of your intermediate or root CA. The certificate can rotate freely; the key doesn’t.</p><pre># Extract the SPKI hash from a cert<br>openssl x509 -in cert.pem -pubkey -noout \<br>  | openssl pkey -pubin -outform der \<br>  | openssl dgst -sha256 -binary \<br>  | base64</pre><pre>// ✅ Pin the public key hash, not the certificate<br>const pinnedHashes = {<br>  &#39;api.yourapp.com&#39;: [<br>    &#39;sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=&#39;, // primary<br>    &#39;sha256/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=&#39;, // backup — always have one<br>  ],<br>};</pre><pre>SecurityContext buildPinnedContext() {<br>  final context = SecurityContext(withTrustedRoots: false);<br>  context.setTrustedCertificatesBytes(yourCaBundleBytes); // trust only your CA<br>  return context;<br>}</pre><p>Always maintain a backup pin. One cert rotation without a backup pin locks out every user until you ship a hotfix.</p><p>Wire it into Dio at the HttpClient level:</p><pre>(dio.httpClientAdapter as IOHttpClientAdapter).createHttpClient = () {<br>  final client = HttpClient(context: buildPinnedContext());<br>  client.badCertificateCallback = (cert, host, port) {<br>    final hash = _spkiHash(cert); // compute SHA-256 of SPKI<br>    return pinnedHashes[host]?.contains(hash) ?? false;<br>  };<br>  return client;<br>};</pre><p><strong>MITM detection beyond pinning:</strong></p><p>Proxy detection adds another signal. In payment or auth flows, refuse to operate if a proxy is active:</p><pre>Future&lt;bool&gt; isProxied() async {<br>  final info = await ProxyInfo.getProxySettings();<br>  return info.host != null &amp;&amp; info.host!.isNotEmpty;<br>}</pre><p>This doesn’t catch every attack vector, but it raises the bar significantly for the most common interception setups.</p><h3>3. Auth &amp; Session Security: Treat Tokens Like Radioactive Material</h3><p>JWTs are signed blobs. They’re not encrypted, they’re not revocable by default, and they live in your app’s memory or storage until they expire. Treat them accordingly.</p><p><strong>The storage hierarchy</strong> (most to least secure):</p><ol><li><strong>In-memory only</strong> — lost on restart, ideal for short-lived access tokens</li><li><strong>Secure enclave (Keychain/Keystore)</strong> — hardware-backed on modern devices, survives restarts</li><li><strong>Encrypted SharedPreferences</strong> — software encryption, acceptable for refresh tokens</li><li><strong>SharedPreferences / SQLite plaintext</strong> — never, under any circumstances</li></ol><p>This translates directly into a TokenVault:</p><pre>class TokenVault {<br>  // Access token: memory only<br>  String? _accessToken;<br>  DateTime? _accessExpiry;</pre><pre>  static const _refreshKey = &#39;rt_v2&#39;;</pre><pre>  Future&lt;void&gt; storeTokens(TokenPair tokens) async {<br>    _accessToken = tokens.access;<br>    _accessExpiry = tokens.accessExpiry;</pre><pre>    await storage.write(<br>      key: _refreshKey,<br>      value: tokens.refresh,<br>      aOptions: const AndroidOptions(encryptedSharedPreferences: true),<br>    );<br>  }</pre><pre>  Future&lt;String?&gt; getValidAccessToken() async {<br>    if (_accessToken != null &amp;&amp; DateTime.now().isBefore(_accessExpiry!)) {<br>      return _accessToken;<br>    }<br>    return _refreshAccessToken();<br>  }</pre><pre>  void clearOnLogout() {<br>    _accessToken = null;<br>    _accessExpiry = null;<br>    storage.delete(key: _refreshKey);<br>  }<br>}</pre><p><strong>On biometrics:</strong> biometric auth should be a gate to unlock locally stored material, not a credential sent to your server.</p><pre>final auth = LocalAuthentication();<br>final authenticated = await auth.authenticate(<br>  localizedReason: &#39;Confirm your identity to continue&#39;,<br>  options: const AuthenticationOptions(<br>    biometricOnly: true,<br>    stickyAuth: true,<br>  ),<br>);</pre><pre>if (authenticated) {<br>  // Biometric was the gate — now unlock the actual token<br>  final token = await tokenVault.getValidAccessToken();<br>  // Use token for the network request<br>}</pre><p>The biometric result never leaves the device. Your backend still validates the token, not the biometric outcome.</p><p><strong>Re-validate session integrity on every foreground event:</strong></p><pre>void onAppLifecycleChange(AppLifecycleState state) {<br>  if (state == AppLifecycleState.resumed) {<br>    _validateSessionIntegrity();<br>  }<br>}</pre><pre>Future&lt;void&gt; _validateSessionIntegrity() async {<br>  if (await _isDeviceCompromised()) {<br>    sessionManager.invalidateAndLock();<br>  }<br>}</pre><p>An app that checks integrity only at launch misses attacks that happen while it’s backgrounded.</p><h3>4. Code Obfuscation &amp; Reverse Engineering Defense</h3><p>Flutter’s Dart AOT compilation already strips many symbols, but “harder to reverse” is not the same as “impossible to reverse.” Fridump and jadx work against Flutter apps.</p><p><strong>Enable obfuscation at build time</strong> — this belongs in your CI configuration, not something you remember manually:</p><pre># In your Fastfile or CI pipeline<br>flutter build apk \<br>  --release \<br>  --obfuscate \<br>  --split-debug-info=./debug-symbols/android/</pre><p>Critical: store the debug-symbols output. It&#39;s the only thing that lets you decode obfuscated crash stacks from Crashlytics or Sentry.</p><p><strong>What obfuscation doesn’t cover:</strong></p><ul><li>String literals in Dart source — they survive compilation</li><li>Network traffic — handle that with pinning</li><li>Logic that must be readable at runtime</li></ul><p>For string literals that need protection, XOR encoding at build time is the minimum viable approach:</p><pre>// Not cryptographically secure — raises the effort bar above `strings`<br>class ObfuscatedString {<br>  static const _key = 0x5A;</pre><pre>  static String decode(List&lt;int&gt; encoded) {<br>    return String.fromCharCodes(encoded.map((b) =&gt; b ^ _key));<br>  }<br>}</pre><pre>// Pre-encode at build time, decode at runtime<br>final endpoint = ObfuscatedString.decode([0x3B, 0x29, 0x35, 0x35, 0x2B, 0x5A]);</pre><p>This is security-through-obscurity — acknowledge it honestly. It forces an attacker to do real work rather than running strings on your binary. For fintech or health apps, add a commercial RASP layer (Guardsquare DexGuard / iXGuard) as a build step. These operate at the bytecode level in ways Dart tooling cannot match.</p><h3>5. Runtime Integrity: Root, Jailbreak &amp; Tamper Detection</h3><p>Your app should know when it’s running in a hostile environment — and respond proportionally.</p><pre>import &#39;package:flutter_jailbreak_detection/flutter_jailbreak_detection.dart&#39;;<br>import &#39;package:device_info_plus/device_info_plus.dart&#39;;</pre><pre>class RuntimeIntegrityChecker {<br>  Future&lt;IntegrityResult&gt; check() async {<br>    final results = await Future.wait([<br>      _checkJailbreakRoot(),<br>      _checkDebuggerAttached(),<br>      _checkEmulator(),<br>      _checkSignatureValid(),<br>    ]);</pre><pre>    return IntegrityResult(<br>      isRooted: results[0],<br>      debuggerPresent: results[1],<br>      isEmulator: results[2],<br>      signatureValid: results[3],<br>    );<br>  }</pre><pre>  Future&lt;bool&gt; _checkJailbreakRoot() async {<br>    try {<br>      return await FlutterJailbreakDetection.jailbroken;<br>    } catch (_) { return false; }<br>  }</pre><pre>  Future&lt;bool&gt; _checkDebuggerAttached() async {<br>    bool isDebug = false;<br>    assert(() { isDebug = true; return true; }());<br>    return isDebug; // assert blocks only run in debug builds<br>  }</pre><pre>  Future&lt;bool&gt; _checkEmulator() async {<br>    final info = DeviceInfoPlugin();<br>    if (Platform.isAndroid) {<br>      final android = await info.androidInfo;<br>      return !android.isPhysicalDevice;<br>    }<br>    if (Platform.isIOS) {<br>      final ios = await info.iosInfo;<br>      return !ios.isPhysicalDevice;<br>    }<br>    return false;<br>  }<br>}</pre><p><strong>The response matters as much as the detection.</strong> Don’t crash immediately — that’s easy to detect and bypass with Frida. Instead:</p><pre>Future&lt;void&gt; enforceIntegrity() async {<br>  final result = await RuntimeIntegrityChecker().check();</pre><pre>  if (result.isRooted || !result.signatureValid) {<br>    // Report to your backend first — this is forensics data<br>    await _reportIntegrityViolation(result);</pre><pre>    // Rooted = user choice, degrade gracefully (disable features)<br>    // Invalid signature = someone repackaged your app, lock down hard<br>    if (!result.signatureValid) {<br>      await _lockDownAndNotifyUser();<br>    }<br>  }</pre><pre>  if (result.debuggerPresent &amp;&amp; kReleaseMode) {<br>    _exitSilently(); // No dialog, no crash — just exit<br>  }<br>}</pre><p>The distinction between rooted (user choice, handle with nuance) and signature tampered (attacker repackaged your app, lock down completely) is the key design decision most teams miss.</p><h3>6. Secure Local Data: Encryption at Rest</h3><p>If the data is worth protecting, it shouldn’t be readable by pulling the SQLite file from /data/data/your.package/databases/ on a rooted device.</p><p><strong>SQLCipher</strong> gives you AES-256 encryption at the database level:</p><pre>import &#39;package:sqflite_sqlcipher/sqflite_sqlcipher.dart&#39;;</pre><pre>class SecureDatabase {<br>  static Database? _db;</pre><pre>  static Future&lt;Database&gt; get instance async {<br>    _db ??= await _open();<br>    return _db!;<br>  }</pre><pre>  static Future&lt;Database&gt; _open() async {<br>    final key = await _getDatabaseKey(); // derived, never stored raw</pre><pre>    return openDatabaseWithOptions(<br>      join(await getDatabasesPath(), &#39;secure.db&#39;),<br>      options: OpenDatabaseOptions(<br>        version: 1,<br>        password: key,<br>        onCreate: (db, version) async {<br>          await db.execute(&#39;&#39;&#39;<br>            CREATE TABLE sensitive_data (<br>              id INTEGER PRIMARY KEY,<br>              payload BLOB NOT NULL,<br>              created_at INTEGER NOT NULL<br>            )<br>          &#39;&#39;&#39;);<br>        },<br>      ),<br>    );<br>  }</pre><pre>  static Future&lt;String&gt; _getDatabaseKey() async {<br>    final sessionToken = await storage.read(key: &#39;session_binding&#39;);<br>    return _deriveDbKey(sessionToken!); // PBKDF2 again<br>  }<br>}</pre><p>For fields with extreme sensitivity — card numbers, health records, government IDs — layer AES-GCM field encryption on top of the database encryption:</p><pre>import &#39;package:encrypt/encrypt.dart&#39;;</pre><pre>class FieldEncryptor {<br>  final Encrypter _encrypter;</pre><pre>  FieldEncryptor(Uint8List keyBytes)<br>    : _encrypter = Encrypter(AES(Key(keyBytes), mode: AESMode.gcm));</pre><pre>  String encrypt(String plaintext) {<br>    final iv = IV.fromSecureRandom(12); // 96-bit IV for GCM<br>    final encrypted = _encrypter.encrypt(plaintext, iv: iv);<br>    return &#39;${iv.base64}:${encrypted.base64}&#39;; // IV prepended for decryption<br>  }</pre><pre>  String decrypt(String ciphertext) {<br>    final parts = ciphertext.split(&#39;:&#39;);<br>    final iv = IV.fromBase64(parts[0]);<br>    return _encrypter.decrypt64(parts[1], iv: iv);<br>  }<br>}</pre><p>Use AES-GCM, not AES-CBC. GCM is authenticated encryption — it detects ciphertext tampering. CBC is not.</p><h3>7. API Security: Interceptors, Request Signing &amp; Replay Defense</h3><p>Your Dio client is a security boundary, not just an HTTP wrapper.</p><p><strong>Request signing</strong> proves a request originated from your app — not a script that extracted credentials and is replaying them:</p><pre>class RequestSigningInterceptor extends Interceptor {<br>  final String _signingKey;</pre><pre>  RequestSigningInterceptor(this._signingKey);</pre><pre>  @override<br>  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {<br>    final timestamp = DateTime.now().millisecondsSinceEpoch.toString();<br>    final nonce = _generateNonce();<br>    final body = options.data != null ? jsonEncode(options.data) : &#39;&#39;;</pre><pre>    // Canonical string: METHOD|PATH|TIMESTAMP|NONCE|BODY_HASH<br>    final bodyHash = sha256.convert(utf8.encode(body)).toString();<br>    final message = &#39;${options.method}|${options.path}|$timestamp|$nonce|$bodyHash&#39;;<br>    final signature = _hmacSha256(message, _signingKey);</pre><pre>    options.headers.addAll({<br>      &#39;X-Request-Timestamp&#39;: timestamp,<br>      &#39;X-Request-Nonce&#39;: nonce,<br>      &#39;X-Request-Signature&#39;: signature,<br>    });</pre><pre>    handler.next(options);<br>  }</pre><pre>  String _hmacSha256(String message, String key) {<br>    final hmac = Hmac(sha256, utf8.encode(key));<br>    return hmac.convert(utf8.encode(message)).toString();<br>  }</pre><pre>  String _generateNonce() =&gt;<br>    base64Url.encode(List&lt;int&gt;.generate(16, (_) =&gt; Random.secure().nextInt(256)));<br>}</pre><p>On the backend: reject timestamps older than 5 minutes, and store seen nonces in Redis with a matching TTL. That combination eliminates replay attacks.</p><p><strong>Mask sensitive fields in debug logs:</strong></p><pre>class SecureLoggingInterceptor extends Interceptor {<br>  static const _sensitiveKeys = {<br>    &#39;password&#39;, &#39;token&#39;, &#39;secret&#39;, &#39;card_number&#39;,<br>    &#39;cvv&#39;, &#39;pin&#39;, &#39;otp&#39;, &#39;national_id&#39;,<br>  };</pre><pre>  @override<br>  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {<br>    if (kDebugMode) {<br>      debugPrint(&#39;→ ${options.method} ${options.path}: ${_maskSensitive(options.data)}&#39;);<br>    }<br>    handler.next(options);<br>  }</pre><pre>  dynamic _maskSensitive(dynamic data) {<br>    if (data is Map) {<br>      return data.map((k, v) =&gt; MapEntry(<br>        k,<br>        _sensitiveKeys.contains(k.toString().toLowerCase()) ? &#39;***&#39; : _maskSensitive(v),<br>      ));<br>    }<br>    return data;<br>  }<br>}</pre><p>Never log raw request bodies in production. In debug, mask sensitive fields rather than logging nothing — you need to actually debug sometimes.</p><h3>What Most Teams Skip</h3><p>After auditing several Flutter production codebases, the gaps I find most consistently:</p><ul><li><strong>No backup pin</strong> — one cert rotation breaks the app for all users with no hotfix path</li><li><strong>Tokens in SharedPreferences</strong> — flutter_secure_storage exists, there&#39;s no excuse</li><li><strong>Debug logging guards missing</strong> — kDebugMode not wrapping log statements in production builds</li><li><strong>No integrity check at launch</strong> — the app trusts its environment completely</li><li><strong>API keys in </strong><strong>dart-define</strong> — compiled into the binary, extractable in minutes</li><li><strong>Symmetric keys hardcoded</strong> — requires a release to rotate, which means it never gets rotated</li></ul><p>Security is a product feature. It just never appears on the roadmap until something breaks — and by then the damage is done.</p><h3>Packages Referenced</h3><p>Layer Package Key derivation pointycastle Secure storage flutter_secure_storage HTTP client dio Biometrics local_auth Root/jailbreak flutter_jailbreak_detection Device info device_info_plus Encrypted DB sqflite_sqlcipher Field encryption encrypt Hashing crypto</p><p><em>What layers do you ship in production? Anything you’d push back on here? Drop it in the comments — I read all of them.</em></p><p><strong>Tags:</strong> Flutter, Mobile Security, Dart, App Security, Fintech, Mobile Development, Software Engineering, Cybersecurity</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecaf8fef93af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Impeller Tessellation: How Flutter Turns Paths into Triangles]]></title>
            <link>https://medium.com/@mohamed.draz/impeller-tessellation-how-flutter-turns-paths-into-triangles-878ef21d9a3f?source=rss-19decebcc3c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/878ef21d9a3f</guid>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Mohamed Draz]]></dc:creator>
            <pubDate>Fri, 22 Aug 2025 20:17:43 GMT</pubDate>
            <atom:updated>2025-10-06T08:48:20.249Z</atom:updated>
            <content:encoded><![CDATA[<h2>Impeller Tessellation: How Flutter Turns Shapes into Triangles</h2><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*cOHsF5Vckr2bRsI5VWIH7A@2x.jpeg" /></figure><p>Good evening, my fellow Flutter developers!<br> Have you ever wondered how the <strong>Impeller engine</strong> actually renders your widgets under the hood?<br> Let’s dig deep into what really happens inside — it’s way more interesting than just a Canvas.drawPath() call</p><h3>From Skia to Impeller — Why Flutter Made the Switch</h3><p><strong>Before we talk about tessellation, let’s rewind a bit.</strong></p><p>For years, Flutter relied on <strong>Skia</strong> — a powerful open-source 2D graphics engine also used by Chrome and Android.<br> Skia worked well for most cases, but as Flutter grew across <strong>iOS, desktop, and embedded</strong> platforms, a few major issues became clear:</p><ol><li><strong>Shader Compilation Jank:</strong><br> Skia compiles shaders <em>at runtime</em>, meaning the first time a widget is drawn, you might feel a visible “stutter.”<br> This is the infamous <em>Shader Jank</em> developers often complain about.</li><li><strong>Limited Metal Support on iOS:</strong><br> Skia wasn’t designed with Apple’s <strong>Metal API</strong> as a first-class citizen — it mostly used OpenGL, which Apple deprecated.<br> That caused lower performance and compatibility issues on iOS and macOS.</li><li><strong>No Fine-grained Control over GPU Pipelines:</strong><br> Skia is a general-purpose renderer, not built specifically for Flutter’s layered UI architecture.<br> The Flutter team wanted more <strong>predictable performance</strong> and <strong>deterministic rendering</strong> across all devices.</li></ol><p>So, Flutter’s team built <strong>Impeller</strong> — a <strong>custom GPU renderer</strong> written in C++ and Metal/Vulkan.<br> It’s optimized <em>specifically for Flutter’s rendering model</em>, removing runtime shader compilation and giving full control over every GPU stage.</p><p><strong>In short:</strong></p><blockquote><em>Flutter replaced Skia with Impeller to eliminate jank, embrace Metal, and achieve consistent, high-performance rendering across platforms.</em></blockquote><h3>What Is Tessellation?</h3><p><strong>Tessellation</strong> means breaking down a complex shape into a <strong>mesh of triangles</strong>.<br> Why triangles?<br> Because a triangle is the simplest convex shape in 2D — and the GPU loves triangles.<br> Every shader can easily compute color, lighting, and geometry on just 3 vertices.</p><p>So, while we’re drawing with Canvas.drawPath() or CustomPainter, the <strong>GPU doesn’t understand paths or Bezier curves</strong>.<br> All it understands is <strong>triangles</strong>, and that’s where <strong>Tessellation algorithms</strong> come in.</p><h3>The Impeller Rendering Pipeline</h3><p>Here’s how Impeller turns your Path into something the GPU can draw:</p><ol><li><strong>Take the Path</strong> (for example, a circle).</li><li><strong>Break it down into Bezier curve segments.</strong></li><li><strong>Subdivide each segment</strong> into smaller polygons.</li><li><strong>Triangulate</strong> the polygons using a Triangulation Algorithm.</li><li><strong>Send the triangles to the GPU</strong> for rendering.</li></ol><p>During these steps, Impeller uses several smart algorithms :</p><h3>1. Adaptive Subdivision (Approximating Curves)</h3><ul><li>Splits each Bezier curve into multiple straight lines.</li><li>The algorithm checks:</li><li>If the line is <em>close enough</em> to the curve → keep it.</li><li>If not → subdivide more.</li><li>This gives a perfect <strong>balance between accuracy and performance</strong>, avoiding too many triangles.</li></ul><h3>2. Monotone Polygon Partitioning</h3><ul><li>Once you have a complex shape, it gets divided into <strong>monotone polygons</strong> (easier to triangulate).</li><li>This is an <strong>intermediate step</strong> to make the triangulation faster and cleaner.</li></ul><h3>3. Ear Clipping Triangulation</h3><ul><li>A classic but still powerful algorithm.</li><li>It works like this:</li><li>Find an “ear” — a triangle inside the polygon that doesn’t contain other points.</li><li>Clip it out.</li><li>Repeat until the whole shape becomes triangles.</li><li>Complexity: O(n²) in the worst case, but Impeller’s implementation is well optimized.</li></ul><h3>Small Practical Example</h3><p>Imagine you have a <strong>square with a small hole inside</strong>:</p><ul><li><strong>Adaptive Subdivision</strong> converts curves into straight lines.</li><li><strong>Partitioning</strong> splits the shape into simpler pieces.</li><li><strong>Ear Clipping</strong> finally outputs a mesh like this:</li></ul><pre>(0,0) - (100,0) - (100,100)  <br> \         |          /  <br> (0,100) --+---------</pre><p>The result: only 2–3 triangles instead of one huge complex path.</p><h3>Why Should Flutter Developers Care?</h3><p>Because this directly affects your app’s <strong>performance</strong>:</p><ul><li>Complex paths = more tessellation = more triangles = slower rendering.</li><li>You can optimize your CustomPainter like this:</li><li>Simplify your paths (reduce points).</li><li>Use shapes like RRect or Rect instead of very detailed paths.</li><li>In the future, Flutter might expose APIs to control <strong>tessellation levels</strong> manually.</li></ul><h3>Fun Fact</h3><p>Even though <strong>Impeller</strong> solves <strong>shader compilation jank</strong>,<br> <strong>tessellation</strong> is still math-heavy — so heavy UI scenes full of paths still depend on how efficiently these algorithms run.</p><h3>If you enjoyed this deep dive</h3><p>Follow me on <strong>Medium</strong> for more Flutter and graphics-engine insights — <br> where we go beyond widgets and into the <strong>GPU magic</strong> that makes Flutter <em>so fast and beautiful</em>.</p><p><strong>Follow </strong><a href="https://www.linkedin.com/in/draz26648/"><strong>Mohamed Draz</strong></a> for more articles like this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=878ef21d9a3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Investigating Flutter Performance: How to Use DevTools Like a Pro]]></title>
            <link>https://medium.com/@mohamed.draz/investigating-flutter-performance-how-to-use-devtools-like-a-pro-feea23a84611?source=rss-19decebcc3c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/feea23a84611</guid>
            <dc:creator><![CDATA[Mohamed Draz]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 15:57:24 GMT</pubDate>
            <atom:updated>2025-08-01T15:57:24.693Z</atom:updated>
            <content:encoded><![CDATA[<p>When it comes to optimizing Flutter apps, most developers stick to common advice like “use const widgets” or “reduce widget depth.” But if you’re serious about performance, you need to go deeper — into the actual <strong>rendering process</strong> and <strong>frame lifecycle</strong>.</p><p>In this article, we’ll explore how to use <strong>Flutter DevTools</strong> to catch performance bottlenecks that don’t show up in code reviews — things like excessive rebuilds, janky frames, and unnecessary repaints.</p><p>We’ll focus on two specific tools inside DevTools:</p><ul><li><strong>Timeline</strong></li><li><strong>Rebuild Stats / Performance Overlay</strong></li></ul><h3>What Are Performance Bottlenecks in Flutter?</h3><p>Performance bottlenecks are parts of your UI that:</p><ul><li>Rebuild too often</li><li>Repaint unnecessarily</li><li>Take too long to layout or render</li><li>Cause visible frame drops</li></ul><p>And the tricky part?<br> These issues are often <strong>invisible in your IDE</strong> and happen silently during runtime.</p><h3>Why DevTools?</h3><p>Flutter DevTools gives you a real-time, visual breakdown of what’s happening behind the scenes:</p><ul><li>Which widgets are rebuilding</li><li>How long each frame is taking</li><li>Which phases (build, layout, paint, composite) are causing delays</li><li>Whether your UI thread or GPU thread is the bottleneck</li></ul><h3>1. Using the Timeline Tab</h3><p>The <strong>Timeline tab</strong> is your go-to for analyzing frame behavior.</p><p>Each Flutter frame goes through these phases:</p><ol><li>Build</li><li>Layout</li><li>Paint</li><li>Compositing</li><li>Rendering by Skia</li></ol><p>The Timeline shows you the time taken in each phase and highlights frames that exceed the ideal 16ms limit.</p><p><strong>What to look for:</strong></p><ul><li>Build taking 30ms+? Your widget tree may be too deep or dynamic.</li><li>Paint taking too long? You might be drawing offscreen widgets.</li><li>Too many frames marked in red? You’re dropping frames.</li></ul><h3>2. Tracking Rebuilds with Rebuild Stats</h3><p>Another powerful feature is the <strong>Rebuild Stats</strong>, which lets you track:</p><ul><li>How often each widget is rebuilt</li><li>Which widgets are repainting</li><li>Whether these rebuilds are necessary or accidental</li></ul><p>You can also enable Flutter’s built-in PerformanceOverlay or use packages like flutter_redux_dev_tools to visualize rebuilds on-screen.</p><h3>Real-World Example: Unnecessary Rebuilds During Scroll</h3><p>Let’s say you have this widget:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*npoSo_Iu5PzotgW2l65wjA.png" /></figure><p>Now, suppose you place it inside a ListView.builder without using const, a Key, or any optimization.</p><p>Each time you scroll, HeavyWidget is rebuilt — even though nothing has changed.</p><p><strong>DevTools will show you:</strong></p><ul><li>Multiple unnecessary builds</li><li>Increased frame time during scroll</li><li>Potential UI jank if the list is long enough</li></ul><h3>Solution?</h3><ul><li>Use const where possible</li><li>Separate unchanging widgets from dynamic ones</li><li>Use ValueKey or ObjectKey to help Flutter differentiate instances</li><li>Use DevTools to validate your assumptions</li></ul><h3>Conclusion</h3><p>Most Flutter devs only scratch the surface of what DevTools can offer.<br> But when used properly, these tools can:</p><ul><li>Reveal hidden performance issues</li><li>Optimize rendering</li><li>Improve responsiveness</li><li>Help you build smoother, faster apps</li></ul><p>If you found this article helpful and want to see more content about Flutter internals, performance tips, and advanced architecture, feel free to follow me here:<br><strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/draz26648">Mohamed Draz</a></p><p><strong>GitHub</strong>: <a href="http://github.com/draz26648">Mohamed Draz</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=feea23a84611" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Render Loop In Flutter]]></title>
            <link>https://medium.com/@mohamed.draz/render-loop-in-flutter-be5bddf91191?source=rss-19decebcc3c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/be5bddf91191</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Mohamed Draz]]></dc:creator>
            <pubDate>Fri, 04 Oct 2024 13:43:32 GMT</pubDate>
            <atom:updated>2024-10-04T13:43:32.979Z</atom:updated>
            <content:encoded><![CDATA[<p>In Flutter, a <strong>render loop</strong> refers to the continuous cycle where the framework processes updates and renders frames to the screen. It’s an essential part of how Flutter manages and updates the UI, ensuring that any changes in the state of widgets are reflected on the screen in real-time.</p><p>Here’s a breakdown of how the <strong>render loop</strong> works:</p><ol><li><strong>User Interaction or State Change</strong>: When there’s an interaction (e.g., a button press) or a change in state (e.g., updating a value in a State object), Flutter triggers a rebuild for the affected widgets.</li><li><strong>Build Phase</strong>: The widgets that need updating go through the <strong>build phase</strong>, where Flutter constructs new widget trees based on the current state and layout configurations.</li><li><strong>Render Phase</strong>:</li></ol><ul><li>After the build phase, Flutter’s <strong>rendering pipeline</strong> comes into play. The <strong>RenderObject</strong> class represents the actual objects in the layout that Flutter uses to compute the position and size of widgets.</li><li>The framework calculates which parts of the UI need to be updated. This is called the <strong>dirty render objects</strong> (only those that have changed).</li></ul><ol><li><strong>Compositing</strong>: Once Flutter knows what parts of the UI to update, it proceeds to <strong>compositing</strong>, where it combines all the layers of the UI, making it ready for the GPU to draw.</li><li><strong>Paint Phase</strong>: The actual drawing of UI elements happens here, where Flutter sends drawing commands to the GPU to display the visual components on the screen.</li><li><strong>Frame Rendering</strong>: Once everything is processed, the new frame is rendered on the screen. This cycle happens in sync with the device’s screen refresh rate (often 60 frames per second, or 120Hz on high-refresh-rate devices), resulting in smooth animations and updates.</li></ol><h3>Key Points:</h3><ul><li>The <strong>render loop</strong> is constantly running in the background to keep the UI updated.</li><li>Only widgets or portions of the UI that change are rebuilt and re-rendered. This optimization helps in reducing unnecessary computations and maintaining performance.</li><li>Flutter uses a single-threaded event loop for this process, but offloads expensive operations (like image decoding) to background threads.</li></ul><p>The render loop ensures that any changes in your Flutter app are seamlessly reflected without the need for manual updates or refreshes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be5bddf91191" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event loop in Dart and Flutter]]></title>
            <link>https://medium.com/@mohamed.draz/event-loop-in-dart-and-flutter-8d69d1ce14b7?source=rss-19decebcc3c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d69d1ce14b7</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Mohamed Draz]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 13:58:31 GMT</pubDate>
            <atom:updated>2024-09-26T13:58:31.462Z</atom:updated>
            <content:encoded><![CDATA[<p>The <strong>event loop</strong> in Flutter (and Dart) is a crucial part of how asynchronous programming works. It manages how tasks (like UI updates, network requests, timers, etc.) are executed efficiently without blocking the main thread. Here’s a breakdown:</p><h3>How the Event Loop Works:</h3><ol><li><strong>Main Isolate</strong>: Flutter runs most of the app code, including the UI, in a single thread called the main isolate. In Dart, isolates are separate execution contexts that do not share memory but communicate via message passing.</li><li><strong>Event Queue</strong>: The event queue holds tasks that are waiting to be executed. These tasks can be asynchronous events (like I/O operations) or UI updates that need to happen once data is ready.</li><li><strong>Task Execution</strong>: The <strong>event loop</strong> continuously checks the event queue. When the main isolate is free (not busy), it picks up the next task from the event queue and executes it. This prevents blocking the main thread with time-consuming tasks, allowing the app to remain responsive.</li><li><strong>Asynchronous Operations</strong>: When you use Dart’s Future, async, and await keywords, you’re allowing long-running tasks (like network requests or reading files) to run asynchronously. These tasks are added to the event queue, and once the task completes, the event loop picks it up and processes the result.</li><li><strong>Microtasks</strong>: Besides the event queue, Dart has a <strong>microtask queue</strong>. Microtasks are higher priority and are executed before any normal tasks in the event queue. These are usually added using scheduleMicrotask.</li></ol><h3>Key Points:</h3><ul><li>The event loop ensures that long-running tasks (like fetching data) don’t freeze the app’s UI by processing them asynchronously.</li><li>Tasks like UI rendering are processed in the main isolate, while long-running tasks can be processed off the main thread via isolates or as async operations.</li></ul><p>This is essential for building responsive apps in Flutter because it lets the app handle UI updates and asynchronous tasks (e.g., fetching data from a server) smoothly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*z-Whk0gzrOFTrxv9WBFohg.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d69d1ce14b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>