<?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 Juan Diego Campuzano on Medium]]></title>
        <description><![CDATA[Stories by Juan Diego Campuzano on Medium]]></description>
        <link>https://medium.com/@juan-campuzano?source=rss-e09c9322790b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iw21bpRY6PVwCZjUjW95Xw.jpeg</url>
            <title>Stories by Juan Diego Campuzano on Medium</title>
            <link>https://medium.com/@juan-campuzano?source=rss-e09c9322790b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:18:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@juan-campuzano/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[Cutting Test Cycles from Days to Hours: Lessons from Scaling Golden Tests at Bancolombia]]></title>
            <link>https://medium.com/bancolombia-tech/cutting-test-cycles-from-days-to-hours-lessons-from-scaling-golden-tests-at-bancolombia-7f4c8a46a08e?source=rss-e09c9322790b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f4c8a46a08e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Juan Diego Campuzano]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 16:36:06 GMT</pubDate>
            <atom:updated>2026-11-05T16:36:06.620Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How bc_golden_plugin helped us turn visual QA into something we can run, repeat and trust.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gar-NJyfp_pxVHIyE9UXbA.png" /></figure><p>For years, visual QA in our Flutter projects looked the same: a developer finished a component or a screen and scheduled a review with the design team to confirm that it matched the design in Figma. It worked, but it depended on finding a time on everyone’s calendar.</p><p>Then came the moment that changed how we see this process. Last year we migrated our own design system to a new version. The migration took nearly three months. Many of our microfrontends depend on the design system, and the new version came with a lot of breaking changes, so the whole app had to be re-certified visually to make sure everything was still OK.</p><p>And there was a bigger problem. During the migration, we could not generate an APK to test the migrated widgets early. Until every widget was migrated to the new design system and the new Flutter version, there was no test artifact, so we often worked blind until the final regression stage.</p><p>In this article, I will share how we went from that experience to a visual QA process based on golden tests, why we decided to build our own package, <strong>bc_golden_plugin</strong>, what it looks like in practice, the problems we found along the way (CI, I’m looking at you), and the results and lessons we have collected so far.</p><blockquote><em>In a previous article (in Spanish), </em><a href="https://medium.com/bancolombia-tech/utilizando-golden-tests-como-herramienta-de-qa-visual-91ef96cb8ed0"><em>Utilizando Golden Tests como herramienta de QA visual</em></a><em>, I explained what golden testing is, how </em><em>matchesGoldenFile works, and the first version of our package. If you are new to golden tests, start there; this article picks up where that one ended.</em></blockquote><p>Before going further, special thanks go to two teammates: <a href="https://www.linkedin.com/in/john-mario-cabrera-201a35215/">John Mario Cabrera</a>, who has gone all-in on golden testing with me, and <a href="https://www.linkedin.com/in/wensierrasepul0711">Wendy Carolina Sierra Sepulveda</a>. Both reviewed this article, and their observations made it more accurate and complete.</p><h3>How did visual QA work before?</h3><p>Before golden tests, visual QA was a manual and collaborative process:</p><ol><li><strong>Build:</strong> the developer implemented the screen based on the Figma design.</li><li><strong>Schedule:</strong> we booked a review session with the design team.</li><li><strong>Review and fix:</strong> together, we compared the implementation against the design and, if something was off, we fixed it and sometimes scheduled another review.</li></ol><p>The design team supports many areas at the same time, so review slots were shared across all of those requests, and the review stage sometimes took longer than we planned. This was nobody’s fault; the process depended on people being available at the same time, and it did not scale to the number of screens we were building. A migration turns this into something much bigger: it is not just one screen that needs a review; it is the entire app.</p><p>We also had a Look and Feel test suite, but it had its own limits: it depended on the availability of the QA environment and the product APIs. If the environment was down, or a service did not return the state we needed, that scenario simply could not be tested.</p><h3>So… why golden tests?</h3><p>A golden test renders a widget and compares it pixel by pixel against a reference image (the “golden”). This gave us what we were missing:</p><ul><li><strong>Repeatability:</strong> the same check runs the same way every time, without anyone booking a meeting.</li><li><strong>Scale:</strong> re-certifying the whole app becomes a matter of running the test suite and reviewing the diffs, instead of reviewing every screen by hand.</li><li><strong>Early feedback:</strong> goldens run on the widgets themselves, so we can check a migrated component as soon as it exists, without waiting for a full test build of the app.</li><li><strong>More scenarios:</strong> a golden test is purely visual and runs on mocks, so we can cover many more states, such as approved, cancelled, in progress, and failed, without depending on an environment or an API.</li><li><strong>A shared source of truth:</strong> the golden image becomes the agreement between design and development. Once design approves how something looks, the golden test protects it.</li></ul><p>Golden tests did not replace the design team. Their review is still where a golden image gets approved; what changed is that we don’t need to ask for the same review again every time we touch the code.</p><h3>Why did we build our own package?</h3><p>flutter_test already gives you matchesGoldenFile, and there were great packages built on top of it, especially <a href="https://pub.dev/packages/golden_toolkit">golden_toolkit</a> and <a href="https://pub.dev/packages/alchemist">alchemist</a>. Our README says it openly: bc_golden_plugin is heavily inspired by both. Still, we decided to build our own, for two reasons:</p><ul><li><strong>Independence:</strong> we did not want a critical part of our quality process to depend on a third-party package whose roadmap we don’t control.</li><li><strong>Missing features:</strong> we needed things that were not available together in one package, like comparing a component directly against a design exported from Figma, an acceptable difference percentage, and ready-to-use device configurations.</li></ul><p>Time proved the first point right. In 2024, the maintainers of golden_toolkit announced that the repository is no longer actively maintained, and the package is now marked as discontinued on pub.dev.</p><p>Today, our package is open source (Apache 2.0), published on pub.dev under bancolombia.com, and its latest version at the time of writing is <strong>3.2.0</strong>.</p><h3>What does it look like in practice?</h3><p>Let’s start with the configuration. A flutter_test_config.dart file in your test folder runs before your tests, so it is a good place to set things up once:</p><pre>// test/flutter_test_config.dart<br>import &#39;dart:async&#39;;<br>import &#39;package:bc_golden_plugin/bc_golden_plugin.dart&#39;;<br>import &#39;package:flutter_test/flutter_test.dart&#39;;<br><br>Future&lt;void&gt; testExecutable(FutureOr&lt;void&gt; Function() testMain) async {<br>  TestWidgetsFlutterBinding.ensureInitialized();<br>  final bcGoldenConfiguration = BcGoldenConfiguration();<br><br>  // The ThemeData your app uses<br>  bcGoldenConfiguration.themeData = AppTheme.light;<br><br>  // Accept up to 0.5% of difference<br>  bcGoldenConfiguration.setThresholdRatio(0.005);<br><br>  // Loads fonts and assets so goldens look like the real app<br>  await loadConfiguration();<br>  await testMain();<br>}</pre><p>That last line matters: as we saw in the previous article, plain golden tests render text with a placeholder font. loadConfiguration loads fonts and assets for us. Now a test for a single component:</p><pre>// test/button_golden_test.dart<br>BcGoldenCapture.single(<br>  &#39;primary_button_golden&#39;,<br>  (tester) async {<br>    await bcWidgetMatchesImage(<br>      imageName: &#39;primary_button&#39;,<br>      widget: const PrimaryButton(label: &#39;Continue&#39;),<br>      tester: tester,<br>      device: GoldenDeviceData.iPhone13,<br>    );<br>  },<br>);</pre><p>bcWidgetMatchesImage renders the widget with the configured theme, in the size and pixel ratio of the selected device. The package ships with several device configurations (iPhone 8, iPhone 13, iPad Pro, Galaxy S25, among others), and you can create your own with bcCustomWindowConfigData.</p><h4>What about accessibility?</h4><p>Many users increase the font size on their phones, and that is where layouts tend to break. With textScaleFactor we can render the component with a bigger font:</p><pre>BcGoldenCapture.single(<br>  &#39;primary_button_large_text_golden&#39;,<br>  (tester) async {<br>    await bcWidgetMatchesImage(<br>      imageName: &#39;primary_button_large_text&#39;,<br>      widget: const PrimaryButton(label: &#39;Continue&#39;),<br>      tester: tester,<br>      device: GoldenDeviceData.iPhone13,<br>      textScaleFactor: 2.0,<br>    );<br>  },<br>);</pre><p>Now overflows and truncated texts show up in a test instead of on a user’s phone.</p><h4>And the Figma comparison?</h4><p>This is the use case that started everything. The reference image can be the design exported from Figma, so the test answers the question we used to ask in the review meeting: “does the implementation look like the design?” Keep in mind that a Figma export and a Flutter render will never be identical pixel by pixel, so this kind of test needs a more generous threshold than a regression test.</p><h3>Why was CI the hardest part?</h3><p>Writing the tests was the easy part. Making them pass in CI was not.</p><p>A golden generated on a developer’s machine can differ slightly from the one rendered in CI. The operating system, font rasterization and anti-aliasing are not exactly the same, so the same widget produces tiny differences that are invisible to the human eye but enough to fail a pixel-by-pixel comparison. At first, this meant tests that passed locally and failed in the pipeline, the fastest way to make a team stop trusting its tests.</p><p>Our solution was to accept a small percentage of difference. The package includes a comparator with a threshold (LocalFileComparatorWithThreshold), and it is initialized automatically with the value from BcGoldenConfiguration when you use bcWidgetMatchesImage or BcGoldenCapture:</p><pre>// As a percentage (0.5%)<br>bcGoldenConfiguration.goldenDifferenceThreshold = 0.5;<br><br>// Or as a ratio (0.005 = 0.5%)<br>bcGoldenConfiguration.setThresholdRatio(0.005);<br><br>// Decide whether a difference above the threshold fails the test<br>bcGoldenConfiguration.willFailOnError = true;</pre><p>With this, rendering noise stays below the threshold and real visual changes still fail the test.</p><p>Later, we went one step further: in the app, the reference images are now generated in the pipeline itself. Since the goldens are created in the same environment where they are compared, those rendering differences disappear, and today our goldens pass without false positives.</p><h3>How do we run them in CI and keep the results?</h3><p>Removing the false positives was only half of the work. A failing test is useful only if someone can quickly see why it failed, and a passing test is worth more when you can prove what it checked.</p><h4>Running the tests in CI</h4><p>Our pipelines run on Azure, and the golden tests run there as one more step of the pipeline. Most of our projects run them on Linux agents, while the design system runs them on macOS. What matters is not which operating system you pick, but that the goldens are generated and compared on the same one. A simplified version of the step looks like this:</p><pre>- script: flutter test<br>  displayName: Run golden tests</pre><h4>Where do the results go?</h4><p>When a golden test fails, Flutter’s file comparator writes the evidence to a failures folder next to the test: the expected image (_masterImage), the rendered one (_testImage), and two difference images (_isolatedDiff and _maskedDiff). Those files are exactly what a reviewer needs, so we do not leave them inside the agent. We publish them as pipeline artifacts:</p><pre>- task: PublishPipelineArtifact@1<br>  displayName: Publish golden results<br>  condition: always() # publish even when the tests pass<br>  inputs:<br>    targetPath: &#39;$(Build.SourcesDirectory)/test&#39;<br>    artifact: &#39;golden-results&#39;</pre><p>Downloading an artifact and opening images one by one still takes time, so we built an internal Azure DevOps extension that turns those results into a report. It adds a new <strong>Report</strong> tab to the pipeline run, where you can see the expected image, the rendered image and their differences side by side, without leaving Azure DevOps. With it, deciding whether a failure is a real bug or an intended design change takes seconds instead of a meeting.</p><h4>Why keep the results even when the tests pass?</h4><p>It is tempting to publish the images only when something breaks. We learned to keep them every time. A passing run is also evidence: it shows which screens and states were validated, for which version, and what they looked like at that moment. When a visual bug shows up weeks later, we can go back to the run for that version and see whether the screen already looked that way or changed afterwards. And when a package goes through certification, that history is what lets us show what was checked instead of only saying that the tests were green. That traceability is what turns golden tests from a development tool into part of our QA process.</p><h3>From single widgets to full flows and animations</h3><p>The first API of the package, bcGoldenTest, worked well for individual components, but it fell short of what we wanted to test. A screen is not only how it looks at rest; it is also how it moves and how it connects with the next screen. So we added a unified API, BcGoldenCapture, with three entry points: single, multiple and animation. The legacy bcGoldenTest is still supported but deprecated.</p><h4>How do you test a full flow in one golden?</h4><p>With BcGoldenCapture.multiple, each step of a flow is captured and all the captures are combined into a single golden image:</p><pre>BcGoldenCapture.multiple(<br>  &#39;onboarding_flow_golden&#39;,<br>  [<br>    GoldenStep(<br>      stepName: &#39;Welcome&#39;,<br>      widgetBuilder: () =&gt; const WelcomeScreen(),<br>    ),<br>    GoldenStep(<br>      stepName: &#39;Features&#39;,<br>      widgetBuilder: () =&gt; const FeaturesScreen(),<br>      setupAction: (tester) async {<br>        await tester.tap(find.text(&#39;Next&#39;));<br>        await tester.pump();<br>      },<br>    ),<br>  ],<br>  const GoldenCaptureConfig(<br>    testName: &#39;onboarding_flow&#39;,<br>    layoutType: CaptureLayoutType.horizontal,<br>    spacing: 16.0,<br>  ),<br>);</pre><p>setupAction and verifyAction let you interact with the screen before or after the capture, and the layout can be vertical, horizontal or grid. The result is one image that a designer can review in a single look, much closer to how they think about the experience than a folder of separate screenshots.</p><figure><img alt="Reference image for demonstration purposes, not an actual implementation" src="https://cdn-images-1.medium.com/max/832/1*joqMS0wL6QfSPE4YeMXXrw.png" /></figure><blockquote><em>Illustrative example created by the author. Not real product or customer data. Please don’t reuse it without permission.</em></blockquote><h4>And animations?</h4><p>For animations, BcGoldenCapture.animation captures frames at specific timestamps and places them side by side in one golden:</p><pre>BcGoldenCapture.animation(<br>  &#39;expand_card_animation&#39;,<br>  () =&gt; const ExpandableCard(),<br>  const GoldenAnimationConfig(<br>    testName: &#39;expand_card_animation&#39;,<br>    totalDuration: Duration(milliseconds: 300),<br>    animationSteps: [<br>      GoldenAnimationStep(timestamp: Duration.zero, frameName: &#39;start&#39;),<br>      GoldenAnimationStep(<br>        timestamp: Duration(milliseconds: 150),<br>        frameName: &#39;middle&#39;,<br>      ),<br>      GoldenAnimationStep(<br>        timestamp: Duration(milliseconds: 300),<br>        frameName: &#39;end&#39;,<br>      ),<br>    ],<br>  ),<br>  animationSetup: (tester) async {<br>    // Trigger the animation<br>    await tester.tap(find.byType(ExpandableCard));<br>    await tester.pump();<br>  },<br>);</pre><p>This is useful for transitions and loading states, where the bug is usually somewhere in the middle.</p><h3>What were the results?</h3><p>These numbers come from our team’s own experience, so take them as approximate figures rather than a formal benchmark:</p><ul><li><strong>Certification time:</strong> on average, certifying a package used to take between 40 and 80 hours, depending on its size. With golden tests, we now certify it in under 2 hours.</li><li><strong>Adoption:</strong> two main areas use the package today: the design system team and the main app team, who are still adding tests.</li><li><strong>Coverage:</strong> together, we are approaching 1,000 golden tests.</li></ul><p>But the biggest change is not in the numbers. Visual QA stopped being an event that we schedule and became something that runs with our test suite, and review time now goes to new designs instead of things that were already approved.</p><h3>Lessons learned and trade-offs</h3><p>Golden tests are not free. These are the main trade-offs we have found:</p><ul><li><strong>Goldens need maintenance:</strong> a large suite means more images to review, store and regenerate, so be selective about what deserves a golden.</li><li><strong>Intentional changes mean regenerating images:</strong> when a design changes on purpose, the goldens must be regenerated, and the new images must be reviewed as carefully as code. Treating --update-goldens as &quot;make the tests green&quot; defeats the whole purpose.</li><li><strong>A threshold can hide real differences:</strong> the acceptable difference percentage solved our CI problem, but a threshold that is too generous can also let small real changes pass, like a slightly different color or a one-pixel shift. The lesson: keep it as low as the environment allows, and consider a different tolerance for Figma comparisons than for regression tests.</li><li><strong>The environment matters:</strong> fonts, platform and Flutter version all affect the render. Without a consistent environment, you will chase false positives instead of real bugs.</li><li><strong>Building your own package has a cost:</strong> independence means we own the maintenance, the documentation and the upgrades for each new Flutter version. For us it is worth it, but it is a decision every team should make consciously.</li></ul><h3>Conclusion</h3><p>Golden tests started for us as a way to avoid waiting for a review meeting. Today they are part of how we build: the design system team uses them to protect components, the main app team keeps adding them to the app’s screens, and re-certifying the whole app after a big change is now something we can check in a fraction of the time.</p><p>More than a testing technique, this marks the maturity of our visual QA process. It moved from depending on people’s availability to depending on automation, and that frees designers and developers to focus on what really needs human judgment: deciding how things should look, not checking again that they still do.</p><p>If you want to dig deeper into the package, I invite you to take a look at the repository on <a href="https://github.com/bancolombia/bc_golden_plugin">GitHub</a> or at <a href="https://pub.dev/packages/bc_golden_plugin">pub.dev</a>. And if you want to read more articles like this one, follow <a href="https://medium.com/bancolombia-tech">Bancolombia Tech</a> on Medium.</p><h3>References</h3><ul><li><a href="https://pub.dev/packages/bc_golden_plugin">bc_golden_plugin on pub.dev</a></li><li><a href="https://github.com/bancolombia/bc_golden_plugin">bancolombia/bc_golden_plugin on GitHub</a></li><li><a href="https://medium.com/bancolombia-tech/utilizando-golden-tests-como-herramienta-de-qa-visual-91ef96cb8ed0">Utilizando Golden Tests como herramienta de QA visual (Bancolombia Tech)</a></li><li><a href="https://api.flutter.dev/flutter/flutter_test/matchesGoldenFile.html">matchesGoldenFile, Flutter API docs</a></li><li><a href="https://pub.dev/packages/golden_toolkit">golden_toolkit on pub.dev (discontinued)</a></li><li><a href="https://github.com/eBay/flutter_glove_box">eBay flutter_glove_box: “This repo is no longer maintained”</a></li><li><a href="https://pub.dev/packages/alchemist">alchemist on pub.dev</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f4c8a46a08e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bancolombia-tech/cutting-test-cycles-from-days-to-hours-lessons-from-scaling-golden-tests-at-bancolombia-7f4c8a46a08e">Cutting Test Cycles from Days to Hours: Lessons from Scaling Golden Tests at Bancolombia</a> was originally published in <a href="https://medium.com/bancolombia-tech">Bancolombia Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dart on the server: A guide to a single source of truth]]></title>
            <link>https://juan-campuzano.medium.com/dart-on-the-server-a-guide-to-a-single-source-of-truth-4a23dc420096?source=rss-e09c9322790b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a23dc420096</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[fullstack-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Juan Diego Campuzano]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 00:07:25 GMT</pubDate>
            <atom:updated>2026-09-28T00:07:25.004Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z3i97vJ5Pncd2BWRR9TY8Q.png" /></figure><p>For years, Flutter developers lived in a dual reality. On mobile and web, we enojoyed the expressive power, strong sound typing, and modern features of Dart. But the moment we needed a backend webhook, a lightweight API, or a Firebase trigger, we inevitably switched context to Typescript, Nodejs or Go.</p><p>With the evolution of <a href="https://pub.dev/packages/firebase_functions">package:firebase_functions</a> and Dart’s official server-side capabilities, the dream of Full-Stack Dart is now a practical reality.</p><p>In this article, I will share the fundamentals of running Dart inside a Firebase Cloud Functions, how to set it up, and a real-world implementation based on my experimental project (a service-booking platform codebase).</p><h3>So… Why Dart on the Server?</h3><p>Before jumping into code, why should a Flutter engineer care about server-side Dart instead of standard Node.js or Python? Here are some key points:</p><ul><li><strong>Zero context switching: </strong>Write business logic, validations rules, and async operations in the exact same language you use for your Flutter UI.</li><li><strong>Shared Domain Models (DDD): </strong>Share Data Transfer Objects (DTOs), entities, and value objects between client and server using a shared local package or path dependency (depends on your project structure).</li><li><strong>Sound Type Safety: </strong>Dart’s sound type system prevents an entire class of runtime errors that commonly slip through <a href="https://medium.com/@veenixdev/typescript-and-the-illusion-of-type-safety-72de07417324">TypeScript’s compilation layer.</a></li><li><strong>Dart AOT and Native Performance: </strong>Dart compiles to efficient native machine code or runs on the high-performance Dart VM, yielding fast startup and predictable memory consumption.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3PPQT9gJ-w1vd9gvJK2aA.png" /></figure><h3>The Experimentation App</h3><p>So for this example I’m using a monorepo with the following structure:</p><pre>experiment_app/<br>├── app/                  # Flutter mobile &amp; web client<br>│   ├── lib/<br>│   └── pubspec.yaml<br>├── functions/            # Dart Cloud Functions<br>│   ├── bin/<br>│   │   └── server.dart   # Function entry point<br>│   ├── functions.yaml    # Firebase function manifest<br>│   ├── pubspec.yaml      # Dependencies (firebase_functions)<br>│   └── analysis_options.yaml<br>├── firebase.json<br>└── .firebaserc</pre><p>Let’s start digging on some of this files:</p><h4>The pubspec.yaml Setup</h4><p>Inside functions/pubspec.yaml , we define the required dependencies. The key package is firebase_functions :</p><pre>name: functions<br>description: Cloud Functions for Firebase in Dart<br>version: 0.0.1<br>publish_to: none<br><br>environment:<br>  sdk: ^3.9.0<br><br>dependencies:<br>  firebase_functions: ^0.8.0<br><br>dev_dependencies:<br>  build_runner: ^2.4.0<br>  lints: ^6.0.0<br>  test: ^1.25.0</pre><h4>Entry Point server.dart</h4><p>Unlide Node.js, where each function is often exported from an index.ts file, Dart functions are registered inside a top-level runFunctions() runner within bin/server.dart as following:</p><pre>import &#39;dart:convert&#39;;<br><br>import &#39;package:firebase_functions/firebase_functions.dart&#39;;<br><br>void main() {<br>  runFunctions((firebase) {<br>    // 1. Healthcheck / Public HTTPS Endpoint<br>    firebase.https.onRequest(<br>      name: &#39;helloWorld&#39;,<br>      options: const HttpsOptions(<br>        cors: Cors([&#39;*&#39;]),<br>        maxInstances: Instances(10), // Guard against unexpected spikes<br>        region: Region(SupportedRegion.usCentral1),<br>      ),<br>      (request) async {<br>        return Response(200, body: &#39;Hello from Dart Cloud Functions!&#39;);<br>      },<br>    );<br><br>    // 2. Business Endpoint: Process Service Order<br>    firebase.https.onRequest(<br>      name: &#39;createServiceOrder&#39;,<br>      options: const HttpsOptions(<br>        cors: Cors([&#39;https://serviclick.web.app&#39;]),<br>        maxInstances: Instances(5),<br>      ),<br>      _handleCreateOrder,<br>    );<br>  });<br>}<br><br>Future&lt;Response&gt; _handleCreateOrder(Request request) async {<br>  if (request.method != &#39;POST&#39;) {<br>    return Response(405, body: &#39;Method Not Allowed&#39;);<br>  }<br><br>  try {<br>    final payload = await request.readAsString();<br>    // Parse payload using shared domain DTOs<br>    // e.g. final order = OrderDto.fromJson(jsonDecode(payload));<br><br>    return Response.ok(<br>      jsonEncode({<br>        &#39;status&#39;: &#39;success&#39;,<br>        &#39;message&#39;: &#39;Order processed via Dart on the server&#39;,<br>        &#39;timestamp&#39;: DateTime.now().toIso8601String(),<br>      }),<br>      headers: {&#39;content-type&#39;: &#39;application/json&#39;},<br>    );<br>  } catch (e) {<br>    return Response(500, body: &#39;Error: $e&#39;);<br>  }<br>}</pre><h4>Sharing Code Between Flutter &amp; Dart Backend</h4><p>The single biggest competitive advantage of Dart on the server is <strong>code sharing.</strong></p><p>Imagine defining a service booking model once:</p><pre>// shared/lib/src/booking.dart<br><br>class ServiceBooking {<br>  final String id;<br>  final String serviceType;<br>  final double amount;<br>  final DateTime scheduledAt;<br><br>  const ServiceBooking({<br>    required this.id,<br>    required this.serviceType,<br>    required this.amount,<br>    required this.scheduledAt,<br>  });<br><br>  bool isValid() =&gt; amount &gt; 0 &amp;&amp; scheduledAt.isAfter(DateTime.now());<br>  <br>  Map&lt;String, dynamic&gt; toJson() =&gt; { ... };<br>  factory ServiceBooking.fromJson(Map&lt;String, dynamic&gt; json) =&gt; ...;<br>}</pre><p>In your Flutter app/ , you import ServiceBooking for your UI Forms and state management. In functions/ , you import the exact same class and run .isValid() before writing to Firestore. <strong>Single source of truth, zero translation layer.</strong></p><h3>Deployment Guide</h3><p>Deploying Dart on Firebase Cloud Functions leverages <strong>Cloud Functions (2nd Gen)</strong>, which is built on top of Google Cloud Run, Cloud Build, and Artifact Registry. <strong>Also it is important to mention that for you to be able to run Firabase Functions you must have Firebase Blaze plan on your project.</strong></p><h4>1. Requirements &amp; Prerequisites</h4><p>Before deploying Dart functions, ensure the following prerequisites are in place:</p><ul><li><strong>Dart SDK</strong>: Dart 3.0 or later (e.g. ^3.9.0).</li><li><strong>Firebase CLI (</strong><strong>firebase-tools)</strong>: Version 13.0.0 or higher.</li></ul><pre>  npm install -g firebase-tools<br>  firebase login</pre><ul><li><strong>Required GCP APIs</strong> (automatically enabled upon first deployment, or manually via Google Cloud Console):</li></ul><pre>cloudfunctions.googleapis.com (Cloud Functions)<br>run.googleapis.com (Cloud Run)<br>cloudbuild.googleapis.com (Cloud Build)<br>artifactregistry.googleapis.com (Artifact Registry)</pre><h4>2. Enable Experimental Dart Support</h4><p>Dart is supported in the Firebase CLI via an experimental feature flag. You must enable it once on your machine:</p><pre>firebase experiments:enable dartfunctions</pre><p>To verify that the feature flag is active:</p><pre>firebase experiments:describe</pre><h4>3. Configure firebase.json</h4><p>In the root of your project (e.g. you-app/firebase.json), point the functions configuration to your functions directory and explicitly specify &quot;runtime&quot;: &quot;dart3&quot;:</p><pre>{<br>  &quot;functions&quot;: [<br>    {<br>      &quot;source&quot;: &quot;functions&quot;,<br>      &quot;codebase&quot;: &quot;default&quot;,<br>      &quot;disallowLegacyRuntimeConfig&quot;: true,<br>      &quot;ignore&quot;: [<br>        &quot;.dart_tool&quot;,<br>        &quot;.git&quot;,<br>        &quot;firebase-debug.log&quot;,<br>        &quot;firebase-debug.*.log&quot;,<br>        &quot;*.local&quot;<br>      ],<br>      &quot;runtime&quot;: &quot;dart3&quot;<br>    }<br>  ]<br>}</pre><p><strong>Tip:</strong> Always include .dart_tool and *.local in the ignore list to prevent uploading unnecessary local build caches during deployment.</p><h4>4. Manifest Generation: functions.yaml</h4><p>Dart Cloud Functions use a declarative manifest (functions.yaml) located in your functions/ folder. This file instructs Google Cloud Build how to package and execute your server binary.</p><p>package:firebase_functions manages this file automatically:</p><pre># Generated by package:firebase_functions. Do not edit manually.<br>specVersion: v1alpha1<br>requiredAPIs:<br>  - api: cloudfunctions.googleapis.com<br>    reason: Required for Cloud Functions<br>endpoints:<br>  hello-world:<br>    platform: gcfv2<br>    region:<br>      - us-central1<br>    maxInstances: 10<br>    httpsTrigger: {}<br>    baseImageUri: us-central1-docker.pkg.dev/serverless-runtimes/google-24/runtimes/osonly24<br>    command:<br>      - ./bin/server<br>    entryPoint: hello-world</pre><p>Notice baseImageUri and command: Cloud Functions uses an ultra-minimal OS base image (osonly24), compiles bin/server.dart into a native binary (./bin/server), and runs it directly.</p><p>To regenerate or validate the manifest after adding new endpoints:</p><pre>cd functions<br>dart pub get<br>dart run firebase_functions:generate</pre><h4>5. Local Testing &amp; Emulation</h4><p>Before pushing to production, test your functions locally using the Firebase Emulator Suite:</p><pre># 1. Fetch dependencies in the functions folder<br>cd functions<br>dart pub get<br><br># 2. Return to project root and start the emulator<br>cd ..<br>firebase emulators:start --only functions</pre><p>Once running, test the local endpoint with curl or Postman:</p><pre>curl http://127.0.0.1:5001/&lt;your-project-id&gt;/us-central1/hello-world<br># Response: Hello from Dart Functions!</pre><h4>6. Deploying to Production</h4><p>When you are ready to ship, execute the Firebase deploy command from the project root:</p><pre># Deploy all functions defined in functions/bin/server.dart<br>firebase deploy --only functions</pre><h4>Deploying Specific Functions</h4><p>If you maintain multiple functions and only want to update one without rebuilding everything, pass the function name:</p><pre>firebase deploy --only functions:hello-world</pre><h4>What Happens During Deployment:</h4><ol><li>The Firebase CLI packages the functions/ directory, omitting files matched in ignore.</li><li>The source bundle is uploaded to Google Cloud Build, which uses the official Dart buildpack to run dart compile exe bin/server.dart -o bin/server.</li><li>The compiled image is stored in Artifact Registry.</li><li>Cloud Functions (2nd Gen) spins up the Cloud Run service container, hooks up HTTPS triggers and IAM permissions, and outputs the live HTTPS URL.</li></ol><h4>7. Logs &amp; Observability</h4><p>To inspect runtime execution and debug logs:</p><pre># Stream live logs from the terminal<br>firebase functions:log<br><br># Stream logs for a specific endpoint<br>firebase functions:log --only helloWorld</pre><p>You can also view rich metrics (latency, memory consumption, request count) directly in the <strong>Google Cloud Console</strong> under Cloud Run / Cloud Functions.</p><h3>Trade-offs &amp; Current Landscape</h3><p>While full-stack Dart is an incredible boost for developer velocity, it is important to evaluate the trade-offs before migrating every backend workload. The biggest win is obvious: complete language consistency and frictionless code sharing. Being able to share native DTOs, business rules, and validation logic between Flutter and Cloud Functions without generating schemas or maintaining dual models in TypeScript saves immense engineering effort. Moreover, Dart’s native compilation and lightweight runtime deliver very competitive cold-start times and predictable memory consumption.</p><p>However, the server-side Dart ecosystem is still evolving. Compared to the mature Node.js ecosystem with its vast npm library catalog and full coverage across all Firebase triggers, Dart’s firebase_functions package primarily focuses on core workloads like HTTPS endpoints, Firestore triggers, and Pub/Sub. While third-party integrations (like payment gateways or authentication providers) that provide official Node SDKs might require you to interact directly with REST APIs in Dart, the trade-off is often well worth it for apps where end-to-end type safety and unified architecture are the top priorities.</p><h3>Key Takeaways</h3><ol><li><strong>End-to-End Type Safety &amp; Shared Domain</strong>: The primary superpower of full-stack Dart is sharing native DTOs, entities, and business validation between the Flutter client and Cloud Functions without schema duplication or translation layers.</li><li><strong>Best-Fit Workloads</strong>: Dart on the backend is production-ready for microservices, webhooks, and BFF (Backend-For-Frontend) layers, especially where HTTPS and Firestore triggers form the core architecture.</li><li><strong>Ecosystem Pragmatism</strong>: While the npm ecosystem offers broader third-party SDK coverage, Dart Cloud Functions are the superior choice when unified architecture, lean native compilation, and developer velocity within a Flutter team are the top priorities.</li><li><strong>Validated in Practice</strong>: In real-world testbeds like the example we used here, running Dart across both frontend and backend drastically cuts <a href="https://www.sciencedirect.com/topics/psychology/cognitive-load">cognitive load</a> and maintenance overhead.</li></ol><p>If you enjoy this type of content please don’t hesitate to click the follow button and leave some claps ;)</p><p>This article was originally published in my personal website, click the <a href="https://www.juan-campuzano.dev/blog/dart-on-the-server-a-guide-to-a-single-source-of-truth">link</a> to visit it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a23dc420096" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoupling Material and Cupertino in Flutter: What’s new?]]></title>
            <link>https://juan-campuzano.medium.com/decoupling-material-and-cupertino-in-flutter-whats-new-f584cf411034?source=rss-e09c9322790b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f584cf411034</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Juan Diego Campuzano]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 15:22:28 GMT</pubDate>
            <atom:updated>2026-08-18T15:22:28.469Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2G5KkJpLXicpbHxJsEk_Tw.png" /></figure><p>For years, starting a Flutter project meant importing package:flutter/material.dart or package:flutter/cupertino.dart almost by default. Flutter was born with the promise of painting high-fidelity, custom user interfaces from scratch. To achieve this in its early stages, the development team bundled the two dominant design systems, Google&#39;s Material Design and Apple&#39;s Cupertino directly into the core framework SDK.</p><p>However, as the ecosystem matured and Flutter expanded to Web, Desktop, and embedded systems, this “batteries-included” monolithic approach began to reveal its architectural limitations.</p><p>With the latest releases of Flutter (culminating in <strong>Flutter 3.47</strong>), one of the framework’s most ambitious engineering transitions is complete: <strong>the complete decoupling of Material and Cupertino from the core SDK</strong>, moving them to independent packages (<a href="https://pub.dev/packages/material_ui">material_ui</a> and <a href="https://pub.dev/packages/cupertino_ui">cupertino_ui</a>) hosted on pub.dev.</p><p>In this deep dive, we will analyze why these libraries were coupled in the first place, the technical implications of this architectural split, how the lifecycle of design bugs changes, and how this benefits custom design system implementations.</p><h3>Why were they coupled in the first place?</h3><p>In Flutter’s layered architecture, the <strong>Widgets</strong> library sits directly below the design systems. This layer manages the element tree (Element, Widget, State), focus, gestures, and basic layout structures. Material and Cupertino were built directly on top of this layer.</p><p>The core issue was that certain base components in the Widgets layer required platform-specific visual assets and behaviors to feel &quot;native.&quot; The most prominent example is text input (<a href="https://api.flutter.dev/flutter/widgets/EditableText-class.html">EditableText</a>) and text selection:</p><ul><li><strong>Text Selection Handles:</strong> On Android, text selection requires rendering the classic teardrop-shaped Material handle, while on iOS it uses the blue pin with an magnifying glass magnifier.</li><li><strong>Context Menus:</strong> When copying or pasting text, iOS displays a rounded bubble with condensed typography (Cupertino style), while Android displays a floating bar with distinct drop shadows (Material style).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*oTWnJp0D3HEDpSxo.png" /></figure><p>To resolve this in early versions, the base Widgets layer performed direct imports or implicit delegation to the Material and Cupertino design libraries. This created a <strong>circular dependency</strong> at both the conceptual and code level within the SDK:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CffPxsm_A3eVx_6TWxY9Kw.png" /></figure><p>This loop created a dual-dependency problem:</p><ol><li><strong>Downwards Dependency (Standard Inheritance):</strong> Design libraries like material_ui and cupertino_ui naturally need to import the Widgets layer. They inherit from base classes (such as RenderObjectWidget or StatefulWidget) and use generic primitives to construct styled elements like cards, buttons, and switches.</li><li><strong>Upwards Dependency (The Coupling Problem):</strong> To ensure a plug-and-play developer experience, core components like EditableText automatically handled platform behaviors. If running on Android, it resolved handles using Material’s teardrop design; on iOS, it resolved them using Cupertino’s magnifier design. Because the default configurations were hardcoded directly inside the core, widgets.dart was forced to import material.dart and cupertino.dart to instantiate these default styles.</li></ol><p>As a result, the Flutter core could not compile in isolation without knowing specific details of how Material and Cupertino painted their buttons, handles, or context menus. This tight coupling forced every application, even those with 100% custom branding , to load and instantiate Material and Cupertino classes into memory.</p><h3>The new architecture</h3><p>The decoupling initiative transforms the Widgets layer into a true <strong>Blank Canvas</strong>. Under this new modular architecture, the Flutter SDK core provides &quot;headless&quot; components (pure behavior, zero styling), and the design systems act as pure consumer libraries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rHp2ZEcJmeS9aGgb.png" /></figure><p>To achieve this separation, the Flutter team introduced clean abstractions within the core widget layer:</p><ul><li><strong>Neutral Selection Primitives:</strong> Classes like TextSelectionControls and context menu delegates were refactored to be injected via dependency injection at the application level, freeing EditableText from importing design libraries.</li><li><strong>Abstract Route Transitions:</strong> Platform-specific page transitions (e.g., slide-to-back on iOS or fade-through on Android) were extracted from concrete page route classes and refactored into generic animation delegates. An <a href="https://docs.flutter.dev/release/breaking-changes/decouple-page-transition-builders">example</a>.</li></ul><h3>Technical implications for developers</h3><p>While this modular architecture does not break existing code immediately due to a staged deprecation strategy, it introduces a significant shift in dependency management:</p><ol><li><strong>Explicit pubspec.yaml declaration: </strong>New project templates no longer bundle Material and Cupertino inside the SDK by default. If you want to use Material 3, you must declare it as an explicit package dependency:</li></ol><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  material_ui: ^1.0.0 # Design systems are now standard pub packages</pre><p>2. <strong>Automated Migration with </strong><strong>dart fix: </strong>The Flutter toolchain provides automated tooling to rewrite import statements across your codebase:</p><pre>dart fix --apply --code=migrate_design_widgets</pre><p>3. <strong>Compatibility Bridges: </strong>For legacy third-party packages that still rely on package:flutter/material.dart, Flutter has introduced transitional adapters to route references to the new standalone packages without compile errors. <a href="https://pub.dev/packages/material_ui#step-3-bridge-legacy-dependencies-if-needed">Reference</a>.</p><h3>What happens to material and cupertino bugs?</h3><p>Historically, if you encountered a rendering bug in Material’s DropdownMenu or Cupertino&#39;s CupertinoDatePicker, fixing it was a lengthy process:</p><ol><li>Submit a bug report/PR to the main flutter/flutter monorepo.</li><li>Wait for the core team to merge the PR into the master branch.</li><li>Wait for the quarterly SDK release cycle to promote the fix to the stable channel.</li></ol><p>With decoupling, this release bottleneck is eliminated.</p><ul><li><strong>Independent Versioning:</strong> The design systems live in dedicated packages (e.g., flutter/packages). Each package utilizes semantic versioning.</li><li><strong>Instant Patches:</strong> If a new iOS release introduces a breaking change to Cupertino style, the team can release a patch (e.g., cupertino_ui v1.0.5) to pub.dev immediately. Developers can pull the fix by updating their pubspec.yaml without undergoing a risky, full SDK upgrade.</li></ul><h3>Key advantages for proprietary Design Systems</h3><p>Previously, building a custom design system required either heavily overriding a massive ThemeData configuration or wrapping Material components to hide their default styling. This came with two major drawbacks:</p><ul><li><strong>Abstraction Leaks:</strong> If a component inherited behaviors like the Material ink ripple effect under the hood, you had to write boilerplate code to disable it.</li><li><strong>Token Incompatibilities:</strong> Material enforces its own ColorScheme and typography hierarchy. Mapping custom corporate tokens to these fields was error-prone and restrictive.</li></ul><h4>The benefits under the new model:</h4><ul><li><strong>Headless Component Consumption:</strong> Developers can build custom design tokens and widgets starting directly from headless base primitives. Your button will not inherit ripples, elevation, or shadows unless you explicitly define them.</li><li><strong>Optimized Bundle Size (Tree Shaking):</strong> If your web application does not import material_ui or cupertino_ui packages, the tree-shaker removes them completely. This significantly reduces the final JavaScript bundle size for web applications.</li><li><strong>Decoupled Roadmaps:</strong> Your corporate design system is shielded from upstream spec changes. When Google rolls out updates to the Material Design specifications, your custom components will remain untouched.</li></ul><p>Here’s a short example of how your design system would look like when migrating to this new approach.</p><p><a href="https://github.com/juan-campuzano/design_system_decoupled">GitHub - juan-campuzano/design_system_decoupled</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JFM9IEv5P1vIN9qnS3LWcg.png" /></figure><h3>Conclusion</h3><p>The decoupling of Material and Cupertino marks the architectural maturity of Flutter. It transitions from an opinionated UI toolkit into a highly modular, high-performance <strong>cross-platform rendering engine</strong>.</p><p>By separating design systems from core compilation, Flutter provides a clean slate to build bespoke enterprise design systems with improved performance, faster patch cycles, and reduced technical debt.</p><p>If you enjoy this kind of content don’t forget to subscribe and leave some claps ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f584cf411034" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under the Hood of Hybrid Composition++ (HCPP) in Flutter]]></title>
            <link>https://juan-campuzano.medium.com/under-the-hood-of-hybrid-composition-hcpp-in-flutter-b245ceed2fe6?source=rss-e09c9322790b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b245ceed2fe6</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Juan Diego Campuzano]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 19:09:12 GMT</pubDate>
            <atom:updated>2026-07-24T19:09:12.267Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BeQZ9MPFgnlvzxmV.png" /></figure><p>If you’ve ever had to embed a Google Map, a WebView, or a native video player inside a Flutter app, you’ve likely faced the classic Platform View dilemma. You either chose Virtual Display, and watched your native keyboards and accessibility features break, or you opted for Hybrid Composition, only to watch your smooth 120Hz scrolling immediately tank into a janky slideshow.<br>For years, integrating native platform views without a rendering “tax” has been one of Flutter’s hardest engineering challenges. But with the release of Flutter 3.44 and the introduction of Hybrid Composition++ (HCPP), the rules of the game have changed. By leveraging modern Android 14 APIs and Vulkan-backed Impeller rendering, Flutter can now delegate compositing directly to the OS.<br>In this article, we’ll dive deep under the hood of HCPP, explore how it uses SurfaceControl to bypass historical GPU texture copying bottlenecks, and show you how to enable and test it in your own applications.</p><h3>The three eras of Android Platform Views</h3><p>Before diving in into HCPP, let’s first understand what was being used.</p><h4>Virtual Display (VD)</h4><p>In the early days of Flutter, Virtual Display was the default. The Flutter engine creates an off-screen GPU texture. It instructs the Android OS to render the native view (e.g, a Webview) inside this off-screen buffer. Flutter then grabs this texture and paints it inside its own widget tree.</p><p>But Juan, what is an off-screen GPU texture? Great question. Think of it as painting on a separate canvas in a backroom instead of painting directly on the main gallery (the visible screen). The GPU draws all the pixels of the native view onto a private buffer in graphics memory (VRAM) that is invisible to the user. Once completed, the Flutter Engine takes this “canvas” and draws it onto the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FYrrfkFGZ6aA8dJPBvHDVA.png" /></figure><p>So, what are the pros and cons of using this approach?</p><ul><li><strong>Pros: </strong>Excellent rendering performance. Because the native view is treated as a flat texture in memory, Flutter can easily scale, rotate, clip, or apply opacity to ir just like any other widget.</li><li><strong>Cons: </strong>The native view does not physically exist in the screen’s window hierarchy. Touch inputs must be forwarded programmatically, and because the system only sees a raw bitmap texture, it breaks native text selection, keyboard focus, and accessibility services (like TalkBack) which cannot inspect the view’s internal nodes.</li></ul><h4>Hybrid Composition</h4><p>To solve the UX bugs, the Flutter Team introduced Hybrid Composition. Instead of turning the native view into a texture, Flutter places the native view directly into the Android view hierarchy. Flutter then overlays its own canvas around the native view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bhmOElINTkF5Ax0jg4pZBQ.png" /></figure><ul><li><strong>Pros: </strong>100% native fidelity. Keyboard works perfectly, text selection behaves naturally, and accessibility tools read the screen whitout any issue.</li><li><strong>Cons: </strong>Severe performance degradation. To synchronize the frames, Flutter’s Raster Thread and Android’s Platform Thread must merge. Furthermore, every frame requires copying GPU texture buffers back and forth. On many devices, this drops the app’s performance down to 30 FPS or lower, causing visible jank during scrolling.</li></ul><h4><a href="https://github.com/flutter/flutter/wiki/Texture-Layer-Hybrid-Composition/608794a66991736af7f15a9ec85e533c1a7485c5">Texture Layer (TLHC)</a></h4><p>Texture Layer Hybrid Composition (TLHC) arrived as an optimization. It works similarly to Virtual Display but utilizes Android’s hardware-backed SurfaceTexture or ImageReader to stream native frames directly. While it improved keyboard support and performance compared to HC, it still suffered from micro-stutters during fast scrolling and occasional visual clipping artifacts.</p><h3>Under the hood of HCPP</h3><p>Introduced as an opt-in feature in Flutter 3.44, HCPP aims to deliver the holy grail: The performance of Virtual Display with the native fidelity of Hybrid Composition.</p><p>It achieves this by fundamentally changing who is responsible for merging the pixels on screen.</p><p>But before diving into the pipeline, let’s first understand what a <strong>Surface </strong>is in the Android graphic subsystem.</p><ul><li><a href="https://developer.android.com/reference/android/view/Surface"><strong>A raw handle to pixel buffers</strong></a><strong>: </strong>An Android Surface is an object representing the producer side of a buffer queue that feeds into SurfaceLinger (the system compositor).</li><li><strong>The drawing canvas: </strong>When a component (like video player, a Vulkan graphics engine, or a native Android Button) wants to draw pixels, it asks the system for a Surface . The system allocates a pool of raw graphics memory buffer.</li><li><strong>Produces-Consumer Model: </strong>The application acts as the producer (rendering pixels into the Surface), and the operating system acts as the consumer (assembling these raw surfaces together and displaying them on the screen).</li></ul><p>If you think of the physical display as a light table, a <strong>Surface </strong>is like a transparent overhead projector sheet:</p><ul><li>The Flutter Engine draws all of its widgets and UI elements on Sheet A (The Flutter Surface).</li><li>The Android OS draws the native Map or Webview on Sheet B (The Platform View Surface).</li><li>Instead of merging both programmatically, both sheets are stacked on top of each other on the light table <strong>(</strong><a href="https://source.android.com/docs/core/graphics/surfaceflinger-windowmanager"><strong>SurfaceFlinger</strong></a><strong>)</strong>, and the user sees the combined light passing through both transparent sheets simultaneously.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oiFfi8ESp8CDzFz2NotRFw.png" /></figure><p>Here is the step by step pipeline:</p><ol><li><strong>Vulkan &amp; Impeller Rendering: </strong>The Flutter UI is rendered using the new <strong>Impeller</strong> engine, which produces a native graphics Surface backed by Vulkan hardware buffers.</li><li><strong>Native Platform View Surface:</strong> The embedded Android native view (e.g., a Google Map) renders to its own separate native Surface.</li><li><strong>SurfaceControl Synchronization:</strong> Instead of trying to merge these surfaces inside the Flutter code, Flutter packages both the Flutter Surface and the Platform View Surface into a single SurfaceControl transaction.</li><li><strong>SurfaceFlinger Processing:</strong> The SurfaceControl transaction is sent directly to <strong>SurfaceFlinger</strong> (Android&#39;s system-wide display compositor). SurfaceFlinger merges the two layers directly in hardware at the system level before sending the final frame to the physical display.</li></ol><p>By bypassing the need to copy GPU texture buffers back and forth between threads, HCPP eliminates thread-merging jank completely.</p><h3>Hands On Setting up and enabling HCPP</h3><p>The code is also available in the following <a href="https://github.com/juan-campuzano/hybrid_composition_plus_plus">Github Repo.</a></p><p>To test HCPP, you must meet the following requirements:</p><ul><li><strong>Flutter SDK 3.44</strong> or higher.</li><li>An Android device running <strong>Android 14 (API level 34)</strong> or higher.</li><li>A device with <strong>Vulkan</strong> graphics API support.</li><li>The <strong>Impeller</strong> rendering engine active.</li></ul><p>So, the first step is to add this meta-data tag inside the &lt;application&gt; node in android/app/src/main/AndroidManifest.xml</p><pre>&lt;manifest ...&gt;<br>    &lt;application ...&gt;<br>        &lt;meta-data<br>            android:name=&quot;io.flutter.embedding.android.EnableHcpp&quot;<br>            android:value=&quot;true&quot; /&gt;<br>        <br>        &lt;activity ...&gt;<br>            ...<br>        &lt;/activity&gt;<br>    &lt;/application&gt;<br>&lt;/manifest&gt;</pre><p>When integrating your platform view in Dart, use PlatformViewLink along with AndroidViewSurface to ensure it links to the platform-side factory:</p><pre>class AndroidNativeTextHcpp extends StatelessWidget {<br>  final String text;<br><br>  const AndroidNativeTextHcpp({super.key, required this.text});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    const String viewType = &#39;custom-native-text&#39;;<br>    final Map&lt;String, dynamic&gt; creationParams = &lt;String, dynamic&gt;{&#39;text&#39;: text};<br><br>    return PlatformViewLink(<br>      viewType: viewType,<br>      surfaceFactory: (context, controller) {<br>        return AndroidViewSurface(<br>          controller: controller as AndroidViewController,<br>          gestureRecognizers: const &lt;Factory&lt;OneSequenceGestureRecognizer&gt;&gt;{},<br>          hitTestBehavior: PlatformViewHitTestBehavior.opaque,<br>        );<br>      },<br>      onCreatePlatformView: (params) {<br>        return PlatformViewsService.initHybridAndroidView(<br>            id: params.id,<br>            viewType: viewType,<br>            layoutDirection: TextDirection.ltr,<br>            creationParams: creationParams,<br>            creationParamsCodec: const StandardMessageCodec(),<br>            onFocus: () =&gt; params.onFocusChanged(true),<br>          )<br>          ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated)<br>          ..create();<br>      },<br>    );<br>  }<br>}</pre><p>For this example you should also add the following Kotlin components, the NativeTextView</p><pre>package com.example.hybrid_composition_plus_plus<br><br>import android.content.Context<br>import android.view.View<br>import android.widget.TextView<br>import io.flutter.plugin.platform.PlatformView<br><br>class NativeTextView(context: Context, id: Int, creationParams: Map&lt;String?, Any?&gt;?) : PlatformView {<br>    private val textView: TextView = TextView(context)<br><br>    init {<br>        textView.text = creationParams?.get(&quot;text&quot;) as? String ?: &quot;Default Native Text&quot;<br>        textView.textSize = 24f<br>        textView.setPadding(16, 16, 16, 16)<br>    }<br><br>    override fun getView(): View {<br>        return textView<br>    }<br><br>    override fun dispose() {}<br>}</pre><p>And its factory</p><pre>package com.example.hybrid_composition_plus_plus<br><br>import android.content.Context<br>import io.flutter.plugin.common.StandardMessageCodec<br>import io.flutter.plugin.platform.PlatformView<br>import io.flutter.plugin.platform.PlatformViewFactory<br><br>class NativeTextViewFactory : PlatformViewFactory(StandardMessageCodec.INSTANCE) {<br>    override fun create(context: Context, viewId: Int, args: Any?): PlatformView {<br>        val creationParams = args as? Map&lt;String?, Any?&gt;?<br>        return NativeTextView(context, viewId, creationParams)<br>    }<br>}</pre><p>And don’t forget to register the factory in your MainActivity.kt</p><pre>package com.example.hybrid_composition_plus_plus<br><br>import io.flutter.embedding.android.FlutterActivity<br>import io.flutter.embedding.engine.FlutterEngine<br><br>class MainActivity : FlutterActivity(){<br>    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {<br>        super.configureFlutterEngine(flutterEngine)<br>        flutterEngine<br>            .platformViewsController<br>            .registry<br>            .registerViewFactory(&quot;custom-native-text&quot;, NativeTextViewFactory())<br>    }<br>}</pre><p>Then you are ready to try it yourself, it is recommended to use a physicial Android Device with Vulkan Graphics support. You can run the app with the following command:</p><pre>flutter run --profile --enable-hcpp</pre><h3>The Fallback Mechanism</h3><p>One of the best design choices in HCPP is its graceful fallback architecture. If a user runs your app on an older device (e.g., Android 12, API 31) or on a device without Vulkan support, the Flutter engine automatically detects this at runtime.</p><p>Instead of crashing or failing to render, Flutter falls back transparently to <strong>Texture Layer Hybrid Composition (TLHC)</strong>. As a developer, you write the integration code once, and Flutter dynamically optimizes the rendering path based on the user’s hardware.</p><p>HCPP represents a massive milestone for Flutter’s maturity on Android. By leveraging modern OS primitives (SurfaceControl and SurfaceFlinger), Flutter has finally broken down the wall between native views and cross-platform UI. If you are building maps, media playback apps, or complex document viewers, it is time to opt-in and experience the jank-free future of platform views.</p><p>If you enjoy this type of content don’t hesitate to click the Follow button and don’t forget to leave a like ;)</p><h4>References</h4><ul><li><strong>Flutter Official Documentation:</strong> <a href="https://docs.flutter.dev/platform-integration/android/platform-views">Hosting native Android views in your Flutter app with Platform Views</a></li><li><strong>Android Developers Reference:</strong> <a href="https://developer.android.com/reference/android/view/Surface">Android Surface API Documentation</a></li><li><strong>Android Developers Reference:</strong> <a href="https://developer.android.com/reference/android/view/SurfaceControl">Android SurfaceControl API Documentation</a></li><li><strong>Android Source Graphics Architecture:</strong> <a href="https://source.android.com/docs/core/graphics/surfaceflinger">SurfaceFlinger and WindowManager Core Architecture</a></li><li><strong>Flutter Engine Source Code:</strong> Platform View implementation guidelines on <a href="https://github.com/flutter/flutter">Flutter GitHub Repository</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b245ceed2fe6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diseñar librerías Flutter como producto: API, versionamiento y calidad]]></title>
            <link>https://medium.com/bancolombia-tech/dise%C3%B1ar-librer%C3%ADas-flutter-como-producto-api-versionamiento-y-calidad-8a94cc98bc6b?source=rss-e09c9322790b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a94cc98bc6b</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[español]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Juan Diego Campuzano]]></dc:creator>
            <pubDate>Mon, 11 May 2026 18:38:22 GMT</pubDate>
            <atom:updated>2026-05-11T18:38:22.053Z</atom:updated>
            <content:encoded><![CDATA[<p>Construir una librería va más allá de publicar un paquete y esperar que la comunidad lo adopte por sí solo. Una buena librería debe ser fácil de usar, confiable, extensible y, sobre todo, mantenible en el tiempo.</p><p>Este artículo está dirigido a quienes construyen o mantienen soluciones reutilizables para otros desarrolladores, y a quienes quieren empezar este proceso, ya sea que la librería sea de manejo interno, o abierta a la comunidad open source. Veremos buenas prácticas sobre estructura interna, versionamiento semántico, documentación y pruebas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n1bUlM6goEubxgMu" /><figcaption>Photo by <a href="https://unsplash.com/@halacious?utm_source=medium&amp;utm_medium=referral">Hal Gatewood</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Estructuración</h3><p>Para estructurar una librería, primero debemos definir si será principalmente visual (Flutter) o si será una herramienta de línea de comandos (Dart). En ambos casos la estructura base es similar, pero el contenido cambia bastante. Veamos un ejemplo de cómo podría verse:</p><pre>my_library/<br>|  lib/<br>|  |  src/<br>|  |  |  ...<br>|  my_library.dart </pre><p>Esto con el fin de que nuestro usuario final solo tenga que hacer lo siguiente:</p><pre>import &#39;package:my_library/my_library.dart&#39;;</pre><p>Ten en cuenta que los archivos que queden directamente dentro de lib/ (y no dentro de src/ ) serán públicos para los usuarios finales. En ese caso, se podría hacer lo siguiente:</p><pre>my_library/<br>|  lib/<br>|  |  src/<br>|  |  |  ...<br>|  my_library.dart // public file<br>|  my_custom_file.dart // ... also a public file</pre><pre>import &#39;package:my_library/my_library.dart&#39;;<br>import &#39;package:my_library/my_custom_file.dart&#39;;</pre><p>Pero entonces, ¿qué debería ir dentro de my_library.dart? Normalmente este archivo se usa como <a href="https://engineering.verygood.ventures/architecture/barrel_files/"><em>barrel file</em></a>, donde se exportan las funcionalidades que queremos exponer de la librería. Sin embargo, si la librería es muy simple, también podrías colocar allí el punto de entrada o incluso parte de la implementación.</p><p>En el caso de usar un <em>barrel file</em>, podríamos tener lo siguiente:</p><pre>my_library/<br>|  lib/<br>|  |  src/<br>|  |  |  models/<br>|  |  |  |  model_1.dart<br>|  |  |  |  model_2.dart<br>|  |  |  |  models.dart<br>|  my_library.dart</pre><pre>// models.dart<br>export &#39;model_1.dart&#39;;<br>export &#39;model_2.dart&#39;;<br><br>// my_library.dart<br>export &#39;src/models/models.dart&#39;;</pre><p>De esta forma, estaríamos cumpliendo con lo que se mencionó anteriormente.</p><p>En cuanto al contenido de la librería, la estructura puede variar de muchas formas dependiendo de la funcionalidad que queremos desarrollar. Algunos ejemplos de librerías pueden ser:</p><h4>Sistemas de diseño</h4><p>Vamos a analizar una librería de componentes muy popular que ha ido tomando fuerza, su nombre es <a href="https://pub.dev/packages/shadcn_ui"><em>shadcn_ui</em></a><em>.</em></p><p>Lo primero que podemos notar en su estructura de carpetas es que tiene un <em>barrel file </em>donde se exporta <strong>todo </strong>el contenido de la librería.</p><p><a href="https://github.com/nank1ro/flutter-shadcn-ui/blob/main/lib/shadcn_ui.dart">flutter-shadcn-ui/lib/shadcn_ui.dart at main · nank1ro/flutter-shadcn-ui</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hY2hLKZ-oXuKW4-rIPTKQg.png" /></figure><p>Lo siguiente que vemos es la estructura del proyecto, al ser una librería de componentes tiene una carpeta components/ en donde está todo el contenido principal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ANYH-NVL0jKYw32BbD3ZUw.png" /></figure><p>Esto puede ser un buen ejemplo si el objetivo es construir una librería basada en componentes visuales. También existen otras estrategias, como Atomic Design, sobre el cual ya tenemos un artículo.</p><p>Si quieres revisar más a profundidad la estructura de <em>shadcn_ui</em>, lo puedes hacer <a href="https://github.com/nank1ro/flutter-shadcn-ui">aquí</a>.</p><p><a href="https://medium.com/bancolombia-tech/c%C3%B3mo-crear-un-sistema-de-dise%C3%B1o-utilizando-atomic-design-en-flutter-6ae0962af4f3">¿Cómo crear un sistema de diseño utilizando Atomic Design en Flutter?</a></p><h4>Líneas de comando (CLI)</h4><p>Para los paquetes de líneas de comandos la estructura es diferente, ya que debemos tener un ejecutable que llame el contenido de nuestra librería.</p><pre>my_package/<br>|  bin/ &lt;- Carpeta donde va el ejecutable<br>|  |  my_package.dart<br>|  lib/<br>|  |  my_package.dart</pre><p>Para crear este tipo de paquetes se puede ejecutar el comando dart create --template=cli &lt;package_name&gt; y con esto tendremos una plantilla inicial para empezar a trabajar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a10073fafbef4b489911f65874e40386/href">https://medium.com/media/a10073fafbef4b489911f65874e40386/href</a></iframe><h3>Buenas prácticas de código</h3><p>Cuando construimos una librería, conviene pensar en ella como si fuera un servicio remoto o una API: debe ser predecible, estable y fácil de consumir. Tus usuarios normalmente interactúan con clases y funciones que exponen parámetros para personalizar la experiencia.</p><p>El equipo de Dart mantiene una guía con buenas prácticas para diseñar librerías. Puedes revisarla <a href="https://dart.dev/effective-dart/design">aquí</a>. Veamos algunos ejemplos de lo que mencionan allí.</p><h4>API expuesta</h4><p>La forma en la que se escriben las clases, parámetros, funciones, etc… tiene un impacto en cómo los usuarios utilizan la librería en su día a día, si usamos nombres que comunican su función podemos facilitar mucho la implementación, un ejemplo:</p><pre>// Api pública<br>class TextWidget extends StatelessWidget{<br>  TextWidget({<br>    required this.text,<br>    this.isVisible = true,<br>  });<br>  <br>  final String text;<br>  final bool isVisible;<br>  <br>  // Build method<br>  ...<br>  <br>}<br><br><br>// Como lo utiliza un usuario<br>class SomeWidget extends StatelessWidget{<br>  @override<br>  Widget build(BuildContext context){<br>    return Scaffold(<br>      body: Column(<br>        children: [<br>          TextWidget(<br>            text: &#39;Hola a todos!&#39;,<br>          ),<br>        ]<br>      ),<br>    );<br>  }<br>}</pre><p>Teniendo esto en cuenta debemos entonces nombrar los parámetros de forma que para el usuario sea natural su interpretación sin necesidad de leer la documentación de la clase. Ahora veamos el ejemplo contrario:</p><pre>// Api pública<br>class TextWidget extends StatelessWidget{<br>  TextWidget({<br>    required this.text,<br>    this.textVisible,<br>  });<br>  <br>  final String text;<br>  final bool textVisible;<br>  <br>  // Build method<br>  ...<br>  <br>}<br><br><br>// Como lo utiliza un usuario<br>class SomeWidget extends StatelessWidget{<br>  @override<br>  Widget build(BuildContext context){<br>    return Scaffold(<br>      body: Column(<br>        children: [<br>          TextWidget(<br>            text: &#39;Hola a todos!&#39;,<br>            textVisible: true,<br>          ),<br>        ]<br>      ),<br>    );<br>  }<br>}</pre><p>De esta forma no es muy intuitivo para el usuario la función del parámetro textVisible ya que no expresa una intención o una acción, lo que hace que el usuario deba indagar lo que hace cada parámetro.</p><h4>Inversión de dependencias</h4><p>En el desarrollo de aplicaciones, solemos usar frameworks como GetIt o Riverpod para gestionar dependencias. Sin embargo, una librería no debe imponer su contenedor de dependencias al usuario. Hacerlo crea un acoplamiento rígido y posibles conflictos de versiones.</p><p>El enfoque correcto es utilizar <strong>Inversión de Dependencias</strong>. La librería debe definir contratos (clases abstractas) y recibir las implementaciones a través del constructor.</p><pre>// En la librería se define el contrato<br>abstract class AuthProvider {<br>  Future&lt;String?&gt; getToken();<br>}<br><br>// Clase principal de la librería<br>class MySDK {<br>  final AuthProvider authProvider;<br><br>  // El usuario puede pasar su propia implementación<br>  MySDK({required this.authProvider});<br>}</pre><p>Gracias a esto las librerías no quedarán acopladas a implementaciones concretas lo que expande su utilidad y transversabilidad a la hora de usarse. De no ser así, cada usuario debería buscar la forma de integrar su implementación en el código fuente de la librería.</p><h4>Documentación</h4><p>Escribir buena documentación en las clases y parámetros también ayuda que la implementación sea mas amigable, Dart ofrece una herramienta para generar documentación en HTML que luego podemos publicar, la herramienta es <a href="https://pub.dev/packages/dartdoc">dart_doc</a>. Un ejemplo de cómo documentar puede ser:</p><pre>/// Analiza cadenas con un formato específico y devuelve un mapa clave-valor.<br>///<br>/// [input] debe estar en el formato `key=value;key=value`.<br>/// Retorna un `Map&lt;String, String&gt;` con las parejas parseadas.<br>///<br>/// Lanza [FormatException] si la cadena es inválida.<br>///<br>/// ### Ejemplo<br>/// ```dart<br>/// final parser = Parser();<br>/// final data = parser.parse(&#39;user=juan;role=admin&#39;);<br>/// // data == {&#39;user&#39;: &#39;juan&#39;, &#39;role&#39;: &#39;admin&#39;}<br>/// ```<br>///<br>/// Desde: v2.4.0<br>class Parser {<br>  /// Si es `true`, activa el nuevo algoritmo de parsing.<br>  ///<br>  /// Valor por defecto: `false`. Será `true` por defecto desde v2.6<br>  /// y el algoritmo anterior se eliminará en v3.0.<br>  final bool enableNewParser;<br><br>  const Parser({this.enableNewParser = false});<br><br>  Map&lt;String, String&gt; parse(String input) {<br>    if (input.trim().isEmpty) {<br>      throw const FormatException(&#39;La cadena no puede estar vacía&#39;);<br>    }<br>    return enableNewParser ? _parseNew(input) : _parseLegacy(input);<br>  }<br><br>  Map&lt;String, String&gt; _parseLegacy(String input) { /* ... */ return {}; }<br>  Map&lt;String, String&gt; _parseNew(String input) { /* ... */ return {}; }<br>}<br><br>/// @deprecated Usa [Parser] con `enableNewParser`.<br>@Deprecated(&#39;Se eliminará en v3.0.0. Usa Parser(enableNewParser: true).&#39;)<br>Map&lt;String, String&gt; parseLegacy(String input) =&gt; {};</pre><h3>Calidad y pruebas automatizadas</h3><p>No se puede confiar mucho en una librería que no se prueba a sí misma. Es importante verificar constantemente su integridad, tanto si es una librería de componentes visuales como si contiene lógica.</p><p>En ambos casos puedes usar el framework de pruebas que viene con el SDK de Flutter: flutter_test. Este incluye utilidades para probar tanto la lógica como la parte visual de los componentes.</p><h4>Golden Tests</h4><p>Como ya hablamos en un artículo anterior, las golden tests son pruebas de regresión visual que le ayudan a los desarrolladores y dueños de producto estar verificando que la capa visual de una aplicación y/o componentes se mantenga en el tiempo, y que no se introduzcan cambios intencionados y rompan esa capa visual. Aquí te muestro un ejemplo de cómo se implementan este tipo de pruebas con la librería <a href="https://pub.dev/packages/bc_golden_plugin">bc_golden_plugin</a>.</p><pre>BcGoldenCapture.single(<br>    &#39;Single test&#39;,<br>    (tester) async {<br>      await bcWidgetMatchesImage(<br>        imageName: &#39;golden_single&#39;,<br>        widget: const HomePage(title: &#39;Flutter Demo Home Page&#39;),<br>        tester: tester,<br>        device: GoldenDeviceData.galaxyS25,<br>      );<br>    },<br>);</pre><p>Si quieres saber mas sobre este tipo de pruebas puedes leer el siguiente artículo:</p><p><a href="https://medium.com/bancolombia-tech/utilizando-golden-tests-como-herramienta-de-qa-visual-91ef96cb8ed0">Utilizando Golden Tests como herramienta de QA visual.</a></p><h4>Unit tests</h4><p>Unit tests validan la lógica de negocio de forma aislada: son rápidos, determinísticos y no dependen de UI, red, disco ni estado global.</p><ul><li><strong>Una buena regla:</strong> si la clase/función no necesita package:flutter/material.dart ni el motor de renderizado, es candidata a unit test. Si involucra widgets, layout o <em>paint</em>, entonces encaja mejor en widget tests (y para ver cambios visuales, en golden tests).</li></ul><p>En librerías, los unit tests son el corazón de la estabilidad del API, capturan el comportamiento público, permiten refactorizar con confianza y reducen el riesgo de <em>breaking changes</em>.</p><p>Algunas buenas prácticas:</p><ul><li>Nombra los tests por comportamiento: whenX_shouldY.</li><li>Estructura: <em>Arrange–Act–Assert</em> o <em>Given–When–Then</em>.</li><li>Cobertura: cubre los casos felices y <em>edge cases</em>. Apunta a +80% de cobertura del código.</li></ul><pre>import &#39;package:test/test.dart&#39;;<br><br>void main(){<br>  test(&#39;When String.trim(), should remove surrounding whitespace&#39;, () {<br>    var string = &#39;  foo &#39;;<br>    expect(string.trim(), equals(&#39;foo&#39;));<br>  });<br>}</pre><h4>Seguridad</h4><p>Una librería que no considera la seguridad como parte de su diseño puede convertirse en el eslabón débil de todas las apps que la consumen.</p><p>Los plugins que incluyen permisos en su AndroidManifest.xml o Info.plist los heredan todas las apps que los consumen. Revisa que tu librería no declare accesos innecesarios a cámara, ubicación o almacenamiento, y documenta explícitamente los que sí requiere.</p><p>Si la librería necesita tokens, URLs de entorno o claves de API, recíbelos como parámetros de inicialización o a través de String.fromEnvironment() con --dart-define en tiempo de build. Nunca los <em>hardcodees</em>.</p><pre>class MySDK {<br>  MySDK({required this.baseUrl, required this.apiKey});<br><br>  final String baseUrl;<br>  final String apiKey;<br>}</pre><p>Una librería no es el objetivo final, pero sí puede ser el vector. El <a href="https://owasp.org/www-project-mobile-top-10/">OWASP Mobile Top 10</a> documenta las vulnerabilidades más frecuentes en apps móviles, y categorías como <em>Insecure Data Storage</em>, <em>Improper Credential Usage</em> o <em>Insufficient Supply Chain Security</em> aplican directamente a decisiones de diseño que tomamos al construir librerías.</p><h3>Versionamiento</h3><p>Es importante definir cómo vamos a versionar nuestra librería incluso antes de empezar a desarrollarla. Existen varias estrategias de versionamiento entre ellas está <a href="https://calver.org/"><em>Calendar Versioning</em></a><em> </em>la cual es recomendada para sistemas y frameworks muy grandes, pero para el caso de librerías se recomienda el uso de <a href="https://semver.org/lang/es/"><em>Semantic Versioning</em></a><em>. </em>Este versionamiento también se puede automatizar con herramientas como</p><p><a href="https://github.com/semantic-release/semantic-release">GitHub - semantic-release/semantic-release: :package::rocket: Fully automated version management and package publishing</a></p><p>que se encargan de generar el CHANGELOG.md basandose en los commits que se integraron a la rama principal del repositorio.</p><p>Mantener un buen registro de los cambios también es importante ya que con esto los usuarios pueden planear si subir la versión de la librería y no les va a implicar alguna reproceso. Veamos un ejemplo de un <strong>mal</strong> CHANGELOG:</p><pre>### [1.0.0]<br>- fix: se hacen cambios # ¿qué cambios?<br>- feat: se agrega nueva funcionalidad # ¿qué funcionalidad?<br>- fix # 🤔</pre><p>Ahora veamos algo más elaborado:</p><pre>### [1.0.0] !12345 &lt;- número del pull request<br>- feat(button): nuevo parametro `color` para cambio de color<br>- fix(input): corrección del foco al iniciar pantalla</pre><p>Este es solo un pequeño ejemplo de cómo podría verse un buen CHANGELOG, lo importante es ser muy descriptivo y conciso de forma que el usuario sepa los cambios que trae una nueva versión. Aquí dejo el <a href="https://github.com/flutter/flutter/blob/master/CHANGELOG.md">CHANGELOG</a> de Flutter como ejemplo.</p><p>Ahora bien, en cuanto al manejo de ramas, hay muchas opciones. Además, dependiendo del equipo de trabajo y de qué tan seguido se vayan a lanzar versiones a producción, conviene usar una metodología u otra. He visto que se utiliza mucho <strong>Trunk-Based Development (TBD)</strong> con ramas release en el caso de librerías, entonces podríamos tener lo siguiente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*Xz_k4xysKqi9LLGLtRJ70w.png" /><figcaption>Ejemplo Trunk-Based Development con Release Branches</figcaption></figure><p>En este ejemplo podemos ver que hay una rama principal llamada Trunk, y que de esta rama salen ramas Feature y Release , las ramas feature son para integrar funcionalidades nuevas, ya sea la evolución de algo existente o se está agregando algo completamente nuevo, incluso, la rama Trunk se considera como una rama inestable, ya que allí pueden haber cambios <strong>breaking </strong>que van a ser desplegados en una versión <em>major </em>posterior. Pero, en este ejemplo ¿cómo puedo evitar integrar un cambio breaking si ese cambio aún no está listo para que los usuarios lo consuman? Esto es muy importante tenerlo en cuenta ya sea para librerías externas o internas, ya que puede generar fricciones entre los desarrolladores, impactando el <strong>Time-To-Market</strong> y la experiencia del desarrollador.</p><p><a href="https://medium.com/bancolombia-tech/feature-flags-de-la-teor%C3%ADa-a-la-pr%C3%A1ctica-a5321db1b513"><em>Feature Flags</em></a> es una técnica que permite activar o desactivar funcionalidades sin necesidad de publicar una nueva versión de la aplicación. En librerías de Flutter, usar banderas de forma simple y localizada es especialmente útil para el versionado: te permite introducir nuevos comportamientos como <a href="https://dictionary.cambridge.org/dictionary/english/opt-in#:~:text=the%20fact%20of%20choosing%20to%20take%20part%20in%20an%20activity%2C%20arrangement%2C%20etc.%20rather%20than%20being%20forced%20to%20take%20part%3A"><em>opt‑in</em></a>, evitar <em>breaking changes</em> y ofrecer una ruta de migración gradual. No se necesita una plataforma compleja de <em>feature flags</em>; basta con exponer <strong>t</strong>oggles claros en la API pública, documentar sus valores por defecto y el plan de retiro. Algunas formas de implementarlo pueden ser:</p><ul><li>Utilizar el decorador @Deprecated que ofrece Dart.</li></ul><pre>@Deprecated(&quot;Este componente se encuentra deprecado.&quot;)<br>class Button extends StatelessWidget{<br>  final String text;<br>  final VoidCallback onPressed;<br>  <br>  Button({required this.text, required this.onPressed});<br>}</pre><ul><li>Realizar cambios con compatibilidad hacia atrás<em>, </em>para darle tiempo a los usuarios de actualizar su implementación.</li></ul><pre>class Button extends StatelessWidget{<br>  @Deprecated(&quot;Parámetro deprecado, usar `content`&quot;)<br>  final String text;<br>  final Widget? content;<br>  final VoidCallback onPressed;<br>  <br>  Button({required this.text, required this.onPressed, this.content});<br><br>  @override<br>  Widget build(BuildContext context){<br>    return ElevatedButton(<br>      child: content != null ? content : Text(text),<br>      onPressed: onPressed<br>    );<br>  }<br>}</pre><ul><li>Si un componente aún no está listo para salir a producción, se puede poner como privado o simplemente no exportarlo en los <em>barrel files, </em>para que los usuarios no lo puedan ver y/o utilizar.</li></ul><h3>Automatizaciones con IA</h3><p>Ya que estamos en el auge de la inteligencia artificial, aquí también dejo algunos tips o consejos que pueden ayudar a mejorar la experiencia del desarrollador cuando se usan ayudas de agentes inteligentes.</p><h4>Copilot instructions o <a href="https://agents.md/">AGENTS.md</a></h4><p>Esto puede servir a la hora de desarrollar librerías o aplicaciones, el objetivo de estos archivos es declarar una serie de reglas que el agente va a inyectar en su ventana de contexto cada que se envíe un prompt, por eso es muy importante no extenderse mucho con estas reglas. En la <a href="https://docs.flutter.dev/ai/ai-rules#device-editor-specific-limits">documentación de Flutter</a> especifican los límites que tiene cada IDE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*ogRoUUilAjX5t6PmY-3l_w.png" /></figure><p>Un ejemplo de cómo podría verse un archivo de instrucciones curado a 1000 tokens sería:</p><pre># Flutter AI Rules<br>**Role:** Expert Dev. Premium, beautiful code.<br>**Tools:** `dart_format`, `dart_fix`, `analyze_files`.<br>**Stack:**<br>* **Nav:** `go_router` (Type-safe).<br>* **State:** `ValueNotifier`. NO Riverpod/GetX.<br>* **Data:** `json_serializable` (snake_case).<br>* **UI:** Material 3, `ColorScheme.fromSeed`, Dark Mode.<br>**Code:**<br>* **SOLID**.<br>* **Layers:** Pres/Domain/Data.<br>* **Naming:** PascalTypes, camelMembers, snake_files.<br>* **Async:** `async/await`, try-catch.<br>* **Log:** `dart:developer` ONLY.<br>* **Null:** Sound safety. No `!`.<br>**Perf:**<br>* `const` everywhere.<br>* `ListView.builder`.<br>* `compute()` for heavy tasks.<br>**Testing:** `flutter test`, `integration_test`.<br>**A11y:** 4.5:1 contrast, Semantics.<br>**Design:** &quot;Wow&quot; factor. Glassmorphism, shadows.<br>**Docs:** Public API `///`. Explain &quot;Why&quot;.</pre><h4><a href="https://agentskills.io/home">Skills</a></h4><p>A diferencia de los <em>instructions</em>, una <em>skill</em> no es solo una función, sino un conjunto de instrucciones, mejores prácticas y flujos de trabajo que le enseñan al agente <em>cómo</em> usar las herramientas para resolver un problema complejo. Por ejemplo una skill para crear un componente dentro de una aplicación:</p><pre>---<br>name: generate-feature<br>description: Genera un nuevo feature (componente) dentro del proyecto Flutter, creando la estructura de carpetas, archivos de páginas, widgets, modelos y rutas siguiendo las convenciones existentes del proyecto. Usar cuando el usuario pida crear un feature, módulo, pantalla o componente nuevo, o cuando mencione agregar una nueva sección a la app.<br>---<br><br># Generar Feature en &lt;Proyecto&gt;<br><br>## Arquitectura del proyecto<br><br>El proyecto usa una arquitectura **feature-first** con las siguientes capas opcionales por feature:<br><br>```<br>lib/features/&lt;feature_name&gt;/<br>├── &lt;feature_name&gt;_route.dart          # Rutas go_router del feature (siempre)<br>├── presentation/<br>│   ├── &lt;feature_name&gt;_page.dart       # Página principal (siempre)<br>│   ├── &lt;otra&gt;_page.dart               # Páginas secundarias (opcional)<br>│   └── widgets/                       # Widgets locales (opcional)<br>│       └── &lt;widget_name&gt;.dart<br>└── domain/                            # Solo si hay modelos<br>    └── models/<br>        └── &lt;model_name&gt;.dart<br>```<br><br>**No existe** capa `data/` en ningún feature. No hay repositorios ni datasources implementados.<br><br>## Convenciones<br><br>### Nomenclatura de archivos<br>- Archivos: `snake_case`<br>- Páginas: sufijo `_page.dart` → clase `PascalCasePage` como `StatelessWidget` o `StatefulWidget`<br>- Rutas: sufijo `_route.dart` → variable `camelCaseRoutes` de tipo `List&lt;RouteBase&gt;`<br>- Widgets: nombre descriptivo `snake_case.dart` → clase `PascalCase`<br>- Modelos: nombre singular `snake_case.dart` → clase `PascalCase`<br><br>### Estado<br>No se usa gestión de estado externa (no Bloc, no Riverpod, no Provider). Solo `StatefulWidget` + `setState()`.<br><br>### Navegación<br>- `go_router` exclusivamente<br>- Navegación con `context.go()` (reemplazo) y `context.push()` (apilado)<br>- Rutas como strings planos: `/&lt;feature&gt;`, `/&lt;feature&gt;/&lt;sub_page&gt;`<br><br>### Dependencias principales<br>- `go_router` para navegación<br>- `google_fonts` para tipografía<br>- No hay barrel files ni exports centralizados<br><br>## Proceso paso a paso<br><br>### 1. Crear la estructura de carpetas<br><br>Crear el directorio del feature y sus subcarpetas:<br><br>```<br>lib/features/&lt;feature_name&gt;/<br>lib/features/&lt;feature_name&gt;/presentation/<br>```<br><br>Si el feature necesita widgets locales:<br>```<br>lib/features/&lt;feature_name&gt;/presentation/widgets/<br>```<br><br>Si el feature necesita modelos:<br>```<br>lib/features/&lt;feature_name&gt;/domain/models/<br>```<br><br>## Checklist final<br><br>- [ ] Carpetas creadas con la estructura correcta<br>- [ ] Página principal del feature creada con `StatelessWidget` o `StatefulWidget`<br>- [ ] Páginas secundarias creadas (si aplica)<br>- [ ] Widgets locales creados en `presentation/widgets/` (si aplica)<br>- [ ] Modelos creados en `domain/models/` (si aplica)<br>- [ ] Archivo `_route.dart` creado con las rutas del feature<br>- [ ] Import agregado en `lib/core/config/routes.dart`<br>- [ ] Spread de rutas agregado en la posición correcta (dentro o fuera de `ShellRoute`)</pre><h4><a href="https://arxiv.org/pdf/2602.00180">Spec-Driven Development</a></h4><p>Es una nueva metodología que ha ido tomando fuerza, en dónde la “fuente de la verdad” no es el código si no uno o varios documentos de especificaciones formales. Con esto entonces se busca que el agente se encargue del código y el desarrollador solo debe definir los requerimientos, diseño y tareas que debe realizar el LLM.</p><p>Esto se puede aplicar en el desarrollo de librerías y/o aplicaciones, ya sea que queramos agregar una funcionalidad nueva, o evolucionar una existente. En el siguiente <a href="https://medium.com/@juan-campuzano/m%C3%A1s-all%C3%A1-del-prompt-spec-driven-development-25bac20edd6a">artículo</a> hablo mas sobre este tema.</p><h3>Conclusiones</h3><p>Construir una librería es, en el fondo, un ejercicio de empatía con el desarrollador que la va a consumir, que muchas veces eres tú mismo en seis meses. Una API predecible, un historial de cambios honesto, pruebas que respalden cada versión y decisiones de seguridad tomadas desde el diseño son lo que separa un paquete útil de uno que genera más preguntas que respuestas. Si este artículo te dio puntos de partida concretos, el siguiente paso es aplicarlos en la próxima librería que construyas o mantengas.</p><p>Si quieres ver más artículos de Bancolombia Tech aquí está el enlace del sitio.</p><p><a href="https://medium.com/bancolombia-tech">Bancolombia Tech</a></p><h3>Referencias</h3><ul><li><a href="https://martinfowler.com/articles/branching-patterns.html">Patterns for Managing Source Code Branches</a></li><li><a href="https://dart.dev/effective-dart">Effective Dart</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a94cc98bc6b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bancolombia-tech/dise%C3%B1ar-librer%C3%ADas-flutter-como-producto-api-versionamiento-y-calidad-8a94cc98bc6b">Diseñar librerías Flutter como producto: API, versionamiento y calidad</a> was originally published in <a href="https://medium.com/bancolombia-tech">Bancolombia Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Más allá del prompt: Spec-Driven Development]]></title>
            <link>https://juan-campuzano.medium.com/m%C3%A1s-all%C3%A1-del-prompt-spec-driven-development-25bac20edd6a?source=rss-e09c9322790b------2</link>
            <guid isPermaLink="false">https://medium.com/p/25bac20edd6a</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Juan Diego Campuzano]]></dc:creator>
            <pubDate>Fri, 13 Mar 2026 00:31:04 GMT</pubDate>
            <atom:updated>2026-03-13T00:34:14.888Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*n2zwGFyA_YVLKA16eT114w@2x.jpeg" /></figure><p>A medida que la inteligencia artificial va evolucionando, nuevos patrones o metodologías emergen. Actualmente, le describes al agente qué es lo que quieres lograr y el agente devuelve una gran cantidad de código, que siendo honestos, muchas veces no es lo que esperamos. Este enfoque de <a href="https://cloud.google.com/discover/what-is-vibe-coding"><em>vibe coding</em></a><em> </em>puede funcionar bien cuando se trata de construir prototipos, pero no muy bien cuando es el momento de construir aplicaciones confiables y de funcionalidades críticas.</p><p>El problema en sí puede que no sea del agente, si no del contexto que le estamos brindando. En la realidad, escribir buenos prompts puede ser complicado y muchos no tenemos esa habilidad desarrollada completamente. Lo que parecen simples instrucciones en lenguaje natural puede dar lugar a muchos resultados posibles si no se hacen buenas <strong>especificaciones.</strong> Incluso en tareas cotidianas como preparar un sandwich de maní, si no se especifican bien las instrucciones de cómo preparlo el resultado puede no ser el esperado, aquí un ejemplo.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFN2RM-CHkuI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFN2RM-CHkuI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FFN2RM-CHkuI%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6efe45efd8e6876c3f49561f6a4dcac6/href">https://medium.com/media/6efe45efd8e6876c3f49561f6a4dcac6/href</a></iframe><h4>Especificaciones</h4><p>Empresas como Amazon con su herramienta <a href="https://kiro.dev/">Kiro</a> y Github con <a href="https://github.com/github/spec-kit">spec-kit</a> están apostando a esta metodología de <em>Desarrollo guiado por especificaciones</em>, en donde la idea principal es que los documentos escritos en lenguaje natural no sean solamente documentos estáticos que utilizamos una vez y no los volvamos a utilizar, si no, que sean la referencia principal con la que el sistema va a seguir evolucionando.</p><p>Entonces, en lugar de escribir código primero y luego documentarlo, en esta metodología, primero se inicia con una especificación. Esa especificación será el contrato sobre cómo el código deberá comportarse y será <strong>la fuente de la verdad </strong>con la que las herramientas de IA que usamos puedan generar, probar y validar el código. El resultado son menos conjeturas, sorpresas y mayor calidad del código.</p><p>Estas especificaciones, a diferencia de los archivos de instrucciones de cada agente o <em>steering files</em>, solamente se agregan a la ventana de contexto cuando las instrucciones que le indicamos al agente implican modificar una funcionalidad de la cuál ya hemos creado las especificaciones, o que vamos a crearlas desde cero. Para ilustrar un poco mejor esto, expongo el siguiente diagrama.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tqZoXoLW_vVDZ7p-EGw_Pg.png" /><figcaption>Memory bank</figcaption></figure><h3>Niveles de Spec-Driven Development</h3><h4>Spec-First</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UwdMeqSIUiT5ciFBkGwZ4w.png" /><figcaption>Spec-First</figcaption></figure><p>En este nivel, el valor que genera la especificación es la claridad que se le da al agente ante algo nuevo. Pero una vez que se genere el código la especificación no se vuelve a usar, en cambio, si se requiere evolucionar la funcionalidad o darle mantenimiento, se debe crear otro archivo de <em>markdown </em>para esto.</p><h4>Spec-Anchored</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92EpwyfOSZkSFxmF2Kwr5w.png" /><figcaption>Spec-Anchored</figcaption></figure><p>Los cambios en la funcionalidad requieren que deba actualizar tanto la especificación como el código. En este nivel la especificación se mantiene para seguirse utilizando en la evolución y/o mantenimiento del código.</p><h4>Spec-As-Source</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnjIsAB_IPYHUH9U8747mA.png" /><figcaption>Spec-As-Source</figcaption></figure><p>Cualquier cambio en la funcionalidad implica que deba actualizar la especificación y deba regenerar el código. Aquí, el desarrollador nunca toca el código, deja que el agente se encargue de eso, y por su parte si requiere actualizar la funcionalidad, debe modificar la especificación.</p><h3>Casos de uso</h3><p>El flujo trabajo se está redefiniendo a medida que los desarrolladores pasan de la codificación manual a la orquestación de especificaciones, la revisión de los resultados de la IA y el enfoque en el diseño de alto nivel. Esta transición aumenta potencialmente la eficiencia, pero introduce nuevos desafíos en torno al mantenimiento de las especificaciones (<em>markdown hell</em>), el dominio de las herramientas y el <strong>criterio</strong> necesario para saber cuándo los resultados de la IA son correctos. Aquí algunos escenarios donde se puede utilizar SDD:</p><ol><li><strong>Proyectos </strong><a href="https://www.productplan.com/glossary/greenfield-project/"><strong>Greenfield</strong></a><strong>: </strong>Cuando se está iniciando un proyecto completamente nuevo, los desarrolladores toman un papel de arquitectos ya que diseñan el sistema a través de especificaciones y no de código. Se centran en la recolección de requisitos, la definición de restricciones y los criterios de aceptación — el “qué” en lugar del “cómo”.</li><li><strong>Funcionalidades nuevas en proyectos existentes: </strong>Aquí es donde la metodología puede aportar mas valor, ya que agregar funcionalidades a un código base muy grande y complejo, puede ser un dolor de cabeza. Con esta metodología se le está indicando al agente qué es todo lo que debe tener en cuenta a la hora de realizar la nueva funcionalidad, cómo se debe integrar en el sistema, qué debe tener en cuenta, etc…</li><li><strong>Modernización de proyecto legados: </strong>Cuando requieres reconstruir un sistema que ya está obsoleto, puede que el contexto o la documentación de cuando se desarrolló, ya se haya perdido. Con esta metodología puedes pedirle al agente que antes de realizar cualquier cambio, capture la “esencia” de la lógica de negocio, para que posteriormente esa sea la base para la modernización del proyecto. Gracias a esto, la IA puede realizar un plan antes de ir a modificar código sin entender bien qué hace cada cosa. La especificación se convierte en el puente entre las implementaciones antiguas y las nuevas.</li></ol><p>Sin embargo también puede pasar que el SDD sea un <em>overkill </em>en algunos escenarios, por ejemplo, crear todo un set de especificaciones para corregir un bug menor, o diseñar un CRUD simple donde es fácil expresar la intención de lo que se quiere construir. En un artículo de <em>arxiv </em>me<em> </em>encontré el siguiente diagrama que ayuda a analizar cuando puede ser viable utilizar esta metodología, al final de este documento dejo anexado el enlace a dicho artículo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*SFJCUsbp2IIZnx3PlBNVMg.png" /></figure><h4>Divide y vencerás</h4><p>La recomendación es que cada tarea debe ser implementable y verificable de forma independiente, similar a como funciona TDD (Test Driven Development) pero para los agentes de IA. Si el agente realiza una tarea que está bien delimitada, ayuda a que el desarrollador solo deba revisar cambios pequeños en lugar de un montón de líneas de código, que a su vez pueden generar mucha carga cognitiva.</p><h3>TODO App con SDD</h3><p>Aquí dejo el <a href="https://github.com/juan-campuzano/todo-sdd">enlace</a> al repositorio en Github.</p><p>Para este ejemplo voy a utilizar <a href="https://github.com/github/spec-kit">Github Spec-Kit</a> que es la opción gratis y open source, para que cualquier pueda utilizarlo.</p><p>Entonces, partiendo de una carpeta vacía (y con el CLI instalado) voy a inicializar el proyecto con el comando specify init . . Aquí el CLI nos pregunta cuál es el agente de nuestra preferencia, en mi caso voy a seleccionar Copilot; esto es relevante ya que dependiendo de la respuesta, el CLI va a generar las carpetas correspondientes para cada agente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0EZFPHt4lelw4L-w81AIvw.png" /></figure><p>Una vez que se seleccione el agente, el CLI crea una serie de archivos de <em>prompt </em>para ejecutar en el IDE con /prompt y los agentes con cada rol definido. Adicional también agrega los templates con los que después va a generar las especificaciones que le indiquemos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_-2zJx7ZkDS5iU4DL2-mAw.png" /></figure><p>Ahora voy ejecutar el <em>prompt </em>speckit.specify &lt;requerimiento&gt; para generar la especificación del menú que va a tener el aplicativo de TODO. Este comando se encarga de crear o actualizar la especificación de una funcionalidad a partir de una descripción en lenguaje natural.</p><p>Una vez que termina de ejecutarse el comando, el agente va a generar los siguientes dos archivos: spec.md y checklists/requirements.md y adicionalmente va a crear una rama asociada con el <em>spec, </em>en este caso 001-todo-menu. En el archivo de especificación van a estar las historias de usuario que el agente considera apropiadas para la característica que le indicamos. Incluso le asigna una prioridad a cada requerimiento según su criterio. Por otra parte el propósito del archivo requirements.md sirve como guía o checklist para revisar los requerimientos generados por el modelo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CHjTtMIch4tlvMXUBRqtsQ.png" /></figure><p>Una vez que revisemos los requerimientos realizados por el agente, nos pregunta si queremos proceder a realizar el plan técnico, o si hay que clarificar mas los requerimientos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lBtRAFPuyuoqsPHNLmXugw.png" /></figure><p>En este caso le diré que prosiga con la creación del plan técnico. Aquí el agente va a empezar a reemplazar los templates que el CLI agregó en la carpeta .specify con la información relacionada al <em>feature.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*tQDS5g3AZX8imoK20AYoOw.png" /></figure><p>El agente también realiza una investigación donde revisa cuáles van a ser la herramientas que va a utilizar para desarrollar la especificación, teniendo cuenta ventajas, desventajas y consideraciones a la hora de implementar. Este archivo se encuentra como research.md .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-R-H6XpMQO7lSpw7VOpGPQ.png" /></figure><p>Ya una vez que revise el plan, investigación y el modelo de datos que el agente va a usar como contexto, puedo pasar a crear las tareas a realizar. Estas tareas van a estar asociadas con las historias de usuario que se crearon en el archivo de especificaciones, de esta forma el agente siempre va a tener contexto del código que está realizando. Aquí un ejemplo de cómo quedaría el archivo de tasks.md .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JfBXhH5Nu1xBqXx9Ayjpzw.png" /></figure><p>Ya una vez que termine de revisar las tareas que se van a ejecutar, puedo pasar la implementación de estas, con el comando speckit.implement , el agente va a tomar los archivos generados en los pasos anteriores y empezará a construir el código. En este caso con el agente que estoy usando (Claude Opus 4.6) él mismo se creó unos Todo’s relacionadas con cada tarea.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*rajFetDwNonY2X0g1A3RXw.png" /></figure><p>Después de realizar todas las tareas el resultado es el siguiente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*1dJ69M28YZijWp7J4vqXmg.gif" /></figure><h3>Conclusiones</h3><p>Con los últimos avances de la tecnología el software ha evolucionado hacia un nivel mas alto de abstracción. Del código de máquina al ensamblador, del ensamblador a los lenguajes de alto nivel, y ahora, de escribir código a escribir la intención. El SDD representa ese siguiente paso, se eleva la abstracción al nivel del sistema, donde el desarrollador declara el qué y el por qué, y la IA materializa el cómo.</p><p>Pero también me deja muchas preguntas como: ¿Se van a revisar archivos <em>markdown </em>en vez de código? ¿Quién es el usuario objetivo, desarrolladores o dueños de producto?</p><p>Una diferencia fundamental de otras metodologías, es que en TDD y BDD, la especificación valida lo que ya fue construido. En SDD, la especificación <strong>guía</strong> lo que va a ser construido.</p><p>Para finalizar, siento que aún faltan cosas por definir, al igual que TDD le tomó años en madurar, ganar herramientas, convenciones, cultura… SDD apenas está encontrando su forma. No es la respuesta final, pero en el momento es la mejor respuesta que tenemos hoy para trabajar con IA de forma disciplinada, y por ahora es suficiente para empezar.</p><h3>Referencias</h3><p>Deepak Babu Piskala. Spec-Driven Development: From Code to Contract <br>in the Age of AI Coding Assistants. arXiv:2602.00180 [cs.SE], 2026. <br><a href="https://arxiv.org/abs/2602.00180">https://arxiv.org/abs/2602.00180</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25bac20edd6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parte 1: Agentic Workflows con Github]]></title>
            <link>https://juan-campuzano.medium.com/parte-1-agentic-workflows-con-github-9abec6edd1ac?source=rss-e09c9322790b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9abec6edd1ac</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Juan Diego Campuzano]]></dc:creator>
            <pubDate>Fri, 06 Mar 2026 00:50:03 GMT</pubDate>
            <atom:updated>2026-03-06T00:50:03.801Z</atom:updated>
            <content:encoded><![CDATA[<p>Imaginemos un mundo donde las mejoras en un repositorio son enviadas automáticamente cada mañana, listas para ser revisadas. Los <em>issues </em>son automáticamente categorizados, fallas en la integración continua analizadas, la documentación se mantiene actualizada y los tests mejorados. Todo esto definido a través de unos simples archivos <em>markdown </em>y que sigue los principios de <a href="https://githubnext.com/projects/continuous-ai">Continuous AI</a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfRMacwSB-ACvl-snQHFow.png" /></figure><h3>Coding Agents, en Github Actions</h3><p>Con coding agents, describes la automatización que quiere realizar en lenguaje natural. En vez de escribir <em>scripts </em>complejos que manejen la categorización de un <em>issue, </em>revisión de código, o manejo de despliegues, simplemente defines lo que quieres que suceda. El agente de IA entiende el contexto del repositorio, interpreta la situación y decide que acciones tomar, todo a partir de una pocas líneas de texto. Veamos un ejemplo:</p><pre>// file: .github/workflows/issue-analyzer.md<br>---<br>on:                        # Trigger: cuándo se ejecuta<br>  issues:<br>    types: [opened]<br><br>permissions: read-all      # Security: solo lectura por defecto<br><br>safe-outputs:              # Operaciones de escritura permitidas<br>  add-comment:<br>---<br># Analizador de Issues<br><br>Analiza el issue actual y pregunta por mas detalles si la solicitud no está clara.</pre><p>Con esto, cada vez que alguien cree un <em>issue </em>en nuestro repositorio, el <em>trigger </em>detectará este evento y ejecutará el contenido de nuestro <em>workflow, </em>en este caso el agente revisará el <em>issue </em>y de no ser muy clara la descripción, le solicitará a la persona que lo realizó que de mas detalles. Si quieres conocer mas detalles sobre la sección de YAML que hay al inicio del archivo puedes leer sobre <a href="https://github.github.io/gh-aw/reference/frontmatter/">frontmatter</a>.</p><p>Pero esto no es todo, adicional a crear el archivo <em>markdown </em>debemos “compilarlo” para que Github lo pueda interpretar como un action. Como bien dice la <a href="https://docs.github.com/es/actions/get-started/quickstart#creating-your-first-workflow">guía de inicio rápido de los Github Actions</a>, estos deben tener como extensión de nombre de archivo el formato YAML/YML. Así que para compilar el <em>markdown </em>que tenemos en lenguaje natural, primero debemos cerciorarnos de tener instalado el CLI de Github. Aquí dejo el <a href="https://github.com/cli/cli#installation">enlace</a> de instalación. Adicional a esto debemos instalar la extensión de los <em>agentic workflows </em>de la siguiente manera:</p><pre>gh extension install github/gh-aw</pre><p>Una vez verifiquemos la instalació del CLI, podemos ejecutar el siguiente comando:</p><pre>gh aw compile</pre><p>Con esto, el CLI va a recorrer la carpeta .github/workflows en busca de archivos <em>markdown </em>que cumplan con el formato del <a href="https://github.github.io/gh-aw/reference/frontmatter/">frontmatter</a> y los va a “compilar” a formato YAML, dando como resultado algo similar a esto:</p><pre># file: .github/workflows/issue-analyzer.lock.yaml<br>jobs:<br>  activation:<br>    run: check authorization<br><br>  agent: needs[activation] # Contenedor aislado<br>    permissions: contents: read # Solo lectura!<br>    run: copilot -p &quot;Analyze package.json for breaking changes...&quot;<br><br>  safe-outputs: needs[agent] # Contenedor aislado<br>    run: gh issue comment add ...<br>    permissions: issues: write</pre><p>Es importante tener en cuenta que cada que se realicen modificaciones al archivo <em>markdown </em>hay que ejecutar el comando que lo compila a formato YAML. De no hacerlo nos va a saltar un error al momento de ejecutar el action indicando que los archivos no están sincronizados.</p><h4>Seguridad</h4><p>Hoy en día es muy importante ser cautelosos con la información que le proveemos a un modelo de inteligencia artificial, y por esto es que Github diseño un entorno seguro en el que el agente se puede ejecutar sin causar repercusiones como eliminar un base de datos por “error”, o reescribir toda una base de código sin una autorización previa. Aquí dejo un diagrama para entender mejor cómo se ejecutan estos flujos de trabajo agénticos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*VS-csUcr-oi3CPl7HkYOtA.png" /><figcaption>Diagrama de seguridad AW</figcaption></figure><ol><li>El agente corre un entorno aislado (sandbox), por defecto solo tiene permisos de lectura y no tiene acceso a hacer modificaciones en el repositorio (crear <em>issues, pull requests…</em>).</li><li>Las peticiones que realiza el agente pasan por un proxy que filtra y verifica que el agente solo llame los dominios permitidos en <a href="https://github.github.io/gh-aw/reference/frontmatter/#network-permissions-network">allowlists</a> .</li><li>Enrutamiento centralizado con un MCP Gateway que administra la comunicación entre el agente y servicios externos, también valida las <em>tools</em> que el modelo invoca.</li><li>Cada <em>tool </em>y MCP invocado por el agente se ejecuta en un contenedor aislado que tiene capas de proxy adicionales para el tráfico de salida.</li></ol><h4>Safe Outputs</h4><p>Las salidas seguras, como su nombre lo dice, <strong>aseguran </strong>que el agente no tenga acceso de escritura a recursos externos, por ejemplo, en el prompt no le podemos indicar que cree un <em>pull request</em> o un <em>issue, </em>esto debe ser indicado en el <em>frontmatter </em>del archivo <em>markdown. </em>De esta forma se garantiza que el agente no pueda modificar ningún aspecto del repositorio si no se le ha indicado en los <em>safe outputs. </em>En el ejemplo que veíamos anteriormente teníamos en los <em>safe outputs </em>el tipo add-comment lo que permite al agente “escribir” un comentario en el <em>issue.</em></p><p>Pero no es el agente quién escribe el comentario si no que, en su salida indica el texto del comentario que quiere escribir, esto pasa por un filtro, y una vez validado se escribe el comentario a través de la API de Github.</p><p>Existen varios tipos de <em>safe outputs, </em>entre ellos existen los <em>handoffs, </em>que también se pueden usar en VSCode localmente, para que la salida de un agente sea la entrada de otro. Por ejemplo podría tener un agente que se encargue de planear los cambios a realizar en un repositorio, y que el resultado de ese agente (ya sea un archivo plano con el plan a ejecutar) se le pase a otro agente que sea especializado en implementar esos cambios. Aquí un ejemplo de cómo se podría ver en los <em>agentic workflows:</em></p><pre>---<br>on:<br>  issues:<br>    types: [opened]<br>safe-outputs:<br>  create-issue:<br>    assignees: [&quot;copilot&quot;]<br>---<br>Analyze issue and break down into implementation tasks</pre><p>Para mas información sobre los tipos de <em>safe outputs, </em>ingresa <a href="https://github.github.io/gh-aw/reference/safe-outputs/">aquí</a>.</p><h4>AI Engines</h4><p>Estos flujos de trabajo soportan múltiples proveedores de IA:</p><ul><li><strong>Github Copilot (Recomendado, por defecto)</strong></li><li>Claude</li><li>Codex</li><li>Gemini</li></ul><blockquote>Cabe resaltar que Github Copilot ofrece soporte para conectar MCP’s</blockquote><p>Para cambiar el motor de IA simplemente en el <em>frontmatter </em>agregamos la siguiente línea:</p><pre>---<br>on:<br>  issues:<br>    types: [opened]<br>safe-outputs:<br>  create-issue:<br>    assignees: [&quot;copilot&quot;]<br>engine: copilot # claude, codex, gemini<br>---</pre><p>En caso de querer usar Claude, debemos generar primero una API Key en la developer platform de Anthropic y setearla con el siguiente comando:</p><pre>gh aw secrets set ANTHROPIC_API_KEY --value &quot;YOUR_ANTHROPIC_API_KEY&quot;</pre><p>También se puede agregar desde la web de Github, dentro del repositorio en la ruta Settings &gt; Secrets and variables &gt; Actions &gt; Repository Secrets. <a href="https://github.github.io/gh-aw/reference/engines/">Aquí puedes encontrar mas información.</a></p><h4>Patrones de diseño</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hWcX_ghfTJKf7GKszESPEg.jpeg" /></figure><p>En esta infografía quise resumir un poco todos los posibles casos de uso que pueden tener estos flujos de trabajo. En esta primera parte quiero abordar solamente lo que son las <em>Trial Ops.</em></p><h4>Trial Ops</h4><p>Es un patrón de diseño para administrar ejecuciones de prueba o experimentaciones, y es que antes de agregar un flujo de trabajo a un repositorio real, podemos ejecutarlo en uno de prueba que simule ser ese repositorio objetivo. Para ejecutar eso localmente simplemente llamamos el siguiente comando:</p><pre>gh aw trial ./.github/workflows/my-workflow.md</pre><p>Con esto podemos verificar que el archivo <em>markdown </em>esté bien formado y no tenga problemas de sintaxis o semánticos en el <em>frontmatter. </em>Al ejecutar este comando sin especificar un repositorio, la línea de comandos nos va a preguntar si queremos crear un repositorio de prueba llamado gh-aw-trial , al aceptar, el CLI crearía el repositorio y subiría allí el <em>workflow</em> para ejecutarlo. En caso de que queramos realizar pruebas en un repositorio sin tener que agregar el <em>workflow </em>o clonarlo manualmente, se puede ejecutar lo siguiente.</p><pre>gh aw trial ./.github/workflows/my-workflow.md --clone-repo myorg/real-repo</pre><p>Esto clona el repositorio para que el <em>workflow </em>pueda acceder al código real sin necesidad de afectar el repositorio real. Para no extender mucho el artículo aquí dejo el enlace sobre <a href="https://github.github.io/gh-aw/patterns/trial-ops/">Trial Ops.</a></p><p>En esta primera parte quise abordar sobre lo que son <em>Agentic Workflows, </em>un poco de su estructura interna y propiedades principales para empezar a construirlos. En los siguientes artículos empezaremos a ver mas casos de uso con funciones mas avanzadas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9abec6edd1ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Utilizando Golden Tests como herramienta de QA visual.]]></title>
            <link>https://medium.com/bancolombia-tech/utilizando-golden-tests-como-herramienta-de-qa-visual-91ef96cb8ed0?source=rss-e09c9322790b------2</link>
            <guid isPermaLink="false">https://medium.com/p/91ef96cb8ed0</guid>
            <category><![CDATA[ingenieria-de-software]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Juan Diego Campuzano]]></dc:creator>
            <pubDate>Thu, 08 Feb 2024 02:42:22 GMT</pubDate>
            <atom:updated>2024-02-08T02:42:22.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*pG-zTduuf-SVktcS7OutKQ.png" /></figure><p>En el dinámico campo del desarrollo de aplicaciones Flutter, cada nueva herramienta que promete mejorar la eficiencia y la calidad captura nuestra atención. En este artículo, abordaremos el concepto de los Golden Tests y cómo su implementación no solo aceleró nuestros tiempos de entrega, sino que también elevó la coherencia y calidad de los componentes que entregamos.</p><h3>¿Qué es el Golden Testing?</h3><p>Según la definición que nos da Flutter, el Golden testing es una técnica utilizada en el ámbito de las pruebas de software para verificar que la salida de una parte del software permanezca sin cambios con el tiempo. En un golden test, se compara una captura actual de un widget o un grupo de widgets, contra una versión “golden” previamente almacenada que se usará como imagen de referencia. la comparación se hace pixel a pixel, por lo que la mínima modificación visual en un componente o pantalla es detectada por el test.</p><h3>Ejemplo:</h3><p>Para facilitar la comprensión de esta definición, tomaré como ejemplo una app bastante sencilla que consta de una sola pantalla con un poco de texto y una imagen, tal como se puede observar a continuación:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*tIme8WAebv_yHva-yORddQ.png" /></figure><p>Supongamos que después de desarrollar esta pantalla, pasamos por un proceso de certificación con el equipo de QA, y acordamos que la pantalla y sus componentes están ok.</p><p>Ahora, para garantizar que la pantalla no experimente cambios visuales no deseados, ya sea debido a ajustes accidentales o a actualizaciones de paquetes, realizamos una captura del resultado actual, utilizando el paquete nativo de Flutter para tests, <em>flutter_test.</em> ¿Cómo haremos esto? Es bastante simple, veámoslo a continuación:</p><pre>testWidgets(&#39;Golden test mi pantalla principal&#39;, (tester) async {<br>  await tester.pumpWidget(const MyApp());</pre><pre>  //Assert<br>  expectLater(<br>    find.byType(MyApp),<br>    matchesGoldenFile(<br>      &#39;goldens/main.png&#39;,<br>    ),<br>  );<br>});</pre><p>Se trata de una prueba de Widget convencional; la diferencia está en que nuestro assert no tiene la forma habitual de “expect” y en su lugar, se utilizará “expectLater”. **Este último permite manejar comportamientos asíncronos para verificar eventos futuros o flujos de datos no sincrónicos. Otra diferencia es la función <em>matchesGoldenFile,</em> en la cual Flutter se encarga de tomar una captura del widget que le pasamos en el <em>tester</em> y compararla contra la imagen que le especificamos en la ruta.</p><p>En nuestro caso, esa imagen aún no existe porque apenas vamos a tomar la captura del <em>golden</em> para guardarla y tenerla como referencia en el futuro. Una vez escribimos nuestro test, Flutter nos ofrece un comando para generar los <em>golden</em> y asegurar que queden almacenados en la ruta que especificamos en la función <strong><em>matchesGoldenFile.</em></strong> El comando es el siguiente:</p><pre>flutter test --update-goldens</pre><p>Este comando recorre los tests que tengan la función <em>matchesGoldenFile</em> y toma las capturas de pantalla de los componentes que estamos renderizando, para guardarlas en la ruta que le especificamos. Entonces, una vez ejecutamos el comando, obtenemos lo siguiente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*E0OI_rU6_sev3MAscZAhww.png" /></figure><p>Y nuestro archivo <em>main.png</em> se verá de la siguiente manera:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*rDCCS4OHLvoOTDe8yzjSaw.png" /></figure><p>Claramente se ve muy diferente a la pantalla que desarrollamos y esto tiene una razón de ser, veamos por qué:</p><ol><li><strong>Tipografías:</strong> las tipografías personalizadas o que vienen por defecto en la aplicación, pueden dibujarse de manera diferente en las diferentes plataformas, incluso entre versiones de Flutter. Por ejemplo, un archivo <em>golden</em> generado en Windows con una tipografía específica, probablemente será diferente al generado por otro sistema operativo. De hecho, en la misma plataforma, si el <em>golden</em> se generó con una versión de Flutter anterior, puede fallar y requerir una captura actualizada. Para evitar estas situaciones, Flutter utiliza una tipografía por defecto llamada ‘Ahem’ que consiste en rectángulos del mismo tamaño, garantizando que el test será agnóstico a la plataforma en la que se está realizando.</li><li><strong>Imágenes:</strong> en general, en las pruebas de Flutter no se cargan las imágenes. Es decir, en un widget test las imágenes normalmente no se cargan porque el entorno es diferente, comparado con el entorno de compilación o desarrollo, donde no se renderiza la aplicación completa, sino solo una parte de ella. Sin embargo, sí es posible cargar las imágenes en las pruebas mediante la carga en caché antes de ejecutarlas.</li></ol><h3>Caso hipotético</h3><p>Ya que aclaramos la definición de lo que es el Golden Testing, hablemos de un caso de uso hipotético donde este tipo de pruebas entran en acción.</p><p>Supongamos que, después de un tiempo y por diferentes razones, a la pantalla que les mostré anteriormente le actualizamos los textos y la aplicación queda de la siguiente forma:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*ig0CaH8qhN-g2ikzPk_RJQ.png" /></figure><p>Teniendo en cuenta este nuevo diseño de la pantalla, veamos como quedó el <em>golden</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*Lj7BZAzhi_16L7Nmto23Eg.png" /></figure><p>En la imagen <strong><em>golden</em></strong> se aprecia notablemente la reducción de texto, por lo tanto, si en ese momento ejecutamos el test con esta modificación y consideramos la primera imagen Golden que obtuvimos, la herramienta detectará estos cambios y, en consecuencia, generará una carpeta llamada “Failures”. En esta carpeta se incluirán 4 imágenes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*UBliqzfQNhpjpYPIn_9HKg.png" /></figure><p><strong>Nota: Los failures empiezan con el nombre del golden con el que se realizó la prueba. Para este caso: “main”.</strong></p><ul><li>main_testImage: esta va a hacer la captura del componente y permite ver cómo está actualmente.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*mcgWq5HmNOPCKYxrGK2PNw.png" /></figure><ul><li>main_masterImage: el <strong><em>golden</em></strong> que tomó como referencia para hacer la comparación vs. el componente actual.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*1ZJAEUvRqnVG4W1kILBW7Q.png" /></figure><ul><li>main_maskedDiff: esta es la diferencia número uno. Aquí la herramienta toma las dos imágenes de arriba y las superpone para resaltar las diferencias.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*wtiBNGxfXUJ-3_QG0w2Qxg.png" /></figure><ul><li>main_isolatedDiff: esta es la diferencia número dos. Es similar a la anterior y permite ver en dónde detectó la diferencias exactamente (lo que no haya cambiado no aparece en la imagen).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*oZYAiKEnNNiwrX_C0EIJAw.png" /></figure><h3>Enfoque</h3><p>Teniendo claro cómo funcionan las Golden Test en Flutter, ¿cuál fue el enfoque que le dimos desde el Sistema de Diseño?</p><p>El objetivo inicial era encontrar una herramienta que permitiera a los desarrolladores realizar el QA visual de los componentes que ellos mismos creaban y pensamos que esto sería posible utilizando los Golden Test. En nuestro caso, los “goldens” serían las imágenes de ejemplo que el equipo de diseño nos proporciona en el Figma del componente, y las compararíamos con lo que se realiza en desarrollo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*8Ixshj-DDF10Cnb9M709_g.png" /></figure><p>Guiados por este enfoque y la necesidad identificada, comenzamos una investigación para determinar si existía algún paquete que se ajustara a nuestras exigencias. En el proceso encontramos varios paquetes que agregaban nuevas funcionalidades a lo que ya estaba nativamente en flutter_test; sin embargo, ninguno de ellos suplía completamente nuestro requerimiento. Por lo tanto, decidimos crear nuestro propio paquete tomando como referencia los que habíamos visto anteriormente.</p><h3>bc_golden_plugin</h3><p>Así nació bc_golden_plugin, un paquete que busca reducir el tiempo en las pruebas de QA, asegurar una mayor calidad en los componentes y encontrar una estrategia para ejecutar las pruebas en el pipeline, sin sobrecargar el repositorio de imágenes.</p><p>Volviendo nuevamente al ejemplo que planteamos inicialmente, esta vez haremos la captura del golden utilizando el paquete bc_golden_plugin, en lugar del nativo de Flutter. Al hacerlo, obtenemos la siguiente imagen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*YPcFhUQTBTZnxpVz3Boyhg.png" /></figure><p>Ahora, podemos ver que las tipografías y las imágenes se ven correctamente en la imagen generada como Golden. A continuación, veamos cómo queda el fragmento de código:</p><pre>bcGoldenTest(<br>    &#39;Bc Golden Plugin pantalla principal&#39;,<br>    (tester) async {<br>      await bcWidgetMatchesImage(<br>        imageName: &#39;golden_plugin&#39;,<br>        widget: const MyApp(),<br>        tester: tester,<br>        device: iPhone13,<br>      );<br>    },<br>  );</pre><p>Este es un ejemplo de cómo serían las pruebas utilizando el paquete bc_golden_plugin. Ahora son un poco más sencillas que las pruebas de widgets normales. La función bcWidgetMatchesImage se encarga de ejecutar las configuraciones necesarias para renderizar todo correctamente. Además, se puede hablar sobre las configuraciones de dispositivos.</p><p>Cuando tengamos esto, hagamos nuevamente el ejemplo de modificar el diseño inicial, aumentando el texto, removiendo la imagen y quitando el botón inferior, para ver qué sucede cuando hacemos la comparación de ambas imágenes. Nuestra aplicación tendría el siguiente aspecto:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*Ybf3EcRhB7rL6bG4my_bRg.png" /></figure><p>Una vez ejecutemos el golden test, el paquete nos va a devolver las siguientes imágenes:</p><p>Test image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*tQy_xh8m2_ulluPFVrcD2A.png" /></figure><p>Master image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*Lkhtja_sCoy9ctwjJcPYpA.png" /></figure><p>Diferencia 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*tTa0KXbf8miez0Kdu1QDVA.png" /></figure><p>Diferencia 2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*9nZ7RslqeOPBAMBfbRopgg.png" /></figure><p>Aquí observamos que el test reconoce la ausencia de la imagen del diseño inicial y el considerable aumento en la cantidad de texto. Sin embargo, hay otra característica que debemos tener en cuenta, pues es complejo desarrollar un componente que tenga una diferencia del 0%. Por lo tanto, una de las funcionalidades que agregamos es la posibilidad de establecer un límite de diferencia para las pruebas. Dicho esto, al concluir el test termina, el paquete nos devuelve el siguiente mensaje:</p><blockquote>Se encontró una diferencia de 25.09843237331389%, pero es un valor aceptable, dado que el porcentaje de aceptación es de 35.0%</blockquote><p>En este caso, el porcentaje de diferencia encontrado fue del 25% aproximadamente. Hemos definido un porcentaje de aceptación del 35%, por lo tanto, el test nos indicará que se ha realizado con éxito. Si porcentaje fuera menor, el test fallará y nos mostrará el porcentaje de diferencia encontrado, junto con las cuatro imágenes que hemos visto anteriormente.</p><p>Otra funcionalidad que consideramos fue evitar llenar el repositorio con imágenes. Para lograrlo, agregamos los archivos .png de los golden en el archivo .gitignore y configuramos las pruebas para que apunten a una imagen inexistente. Así, al ejecutar el pipeline, un script de Dart se encarga de descargar las imágenes en tiempo de ejecución, antes de realizar las pruebas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*H1pEEc4Ju2_JfYFoEox9Ig.png" /></figure><p>Gracias a esta herramienta hemos mejorado la calidad de los componentes que entregamos a nuestros usuarios y continuamos promoviendo la autonomía al momento de desarrollar nuevos componentes.</p><p>Si quieres revisar un poco más sobre este paquete, te invito a que le des un vistazo al repositorio en Github <a href="https://github.com/bancolombia/bc_golden_plugin">https://github.com/bancolombia/bc_golden_plugin</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91ef96cb8ed0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bancolombia-tech/utilizando-golden-tests-como-herramienta-de-qa-visual-91ef96cb8ed0">Utilizando Golden Tests como herramienta de QA visual.</a> was originally published in <a href="https://medium.com/bancolombia-tech">Bancolombia Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>