<?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 Kainã Terto Pereira on Medium]]></title>
        <description><![CDATA[Stories by Kainã Terto Pereira on Medium]]></description>
        <link>https://medium.com/@kaintertopereira?source=rss-2d42e00bd33e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*hS9F7kjxE_WUhm-V.</url>
            <title>Stories by Kainã Terto Pereira on Medium</title>
            <link>https://medium.com/@kaintertopereira?source=rss-2d42e00bd33e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:32:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kaintertopereira/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[Building a PDF Report Generator with React, Puppeteer, NestJS, and Redis]]></title>
            <link>https://medium.com/capyba/building-a-pdf-report-generator-with-react-puppeteer-nestjs-and-redis-87dbd7eb2118?source=rss-2d42e00bd33e------2</link>
            <guid isPermaLink="false">https://medium.com/p/87dbd7eb2118</guid>
            <category><![CDATA[puppeteer]]></category>
            <category><![CDATA[node-js-development]]></category>
            <category><![CDATA[nestjs-provider]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[redis-cluster]]></category>
            <dc:creator><![CDATA[Kainã Terto Pereira]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 13:24:29 GMT</pubDate>
            <atom:updated>2026-04-04T09:43:20.474Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ByhFlHqgWMQHSDlYopJJ1Q.jpeg" /></figure><p><em>How to stop blocking your Node.js event loop and build a PDF generation pipeline that actually scales.</em></p><p>Hey there, fellow developers! 👋</p><p>Ever found yourself in a situation where you need to generate beautiful PDF reports from your web application? Maybe your boss asked for “just a simple export feature” that turned into a complex reporting system? Well, you’re in the right place!</p><p>Today we’re going to build a complete PDF generation system using some pretty awesome tools: React for templating, Puppeteer for PDF generation, NestJS as our backend framework, and Redis for job queuing. Why this stack? Let me tell you why this combo rocks:</p><ul><li><strong>React</strong> gives us the power to create beautiful, dynamic templates using JSX — no more wrestling with HTML strings!</li><li><strong>Puppeteer</strong> handles the heavy lifting of PDF generation with Chrome’s rendering engine.</li><li><strong>NestJS</strong> provides a solid, scalable backend structure with TypeScript support.</li><li><strong>Redis</strong> ensures our PDF generation doesn’t block the main thread and can handle multiple requests.</li></ul><p>Important disclaimer: This isn’t about finding the “perfect” solution — it’s about building something that works well and teaches us some cool concepts along the way. Ready to dive in? Let’s get our hands dirty!</p><p><strong>Making the Right Choices</strong></p><p>When architecting a solution for generating PDFs, the initial instinct is often to reach for a traditional PDF library like pdfkit or jsPDF. But as business requirements inevitably grow — adding custom fonts, complex tabular data, or dynamic charts — drawing coordinate by coordinate quickly becomes an unmaintainable nightmare.</p><p>This is where the architectural combination of <strong>React + Puppeteer</strong> shines.</p><ul><li><strong>Why React makes sense:</strong> Instead of wrangling messy HTML string concatenations or learning niche templating engines (like Pug or EJS), React allows us to leverage existing frontend paradigms on the backend. We can build modular, reusable, strongly-typed components using JSX. By utilizing `ReactDOMServer.renderToStaticMarkup()`, we instantly convert declarative UI components into raw HTML strings ready for rendering.</li><li><strong>Why Puppeteer:</strong> Puppeteer drives a headless Chromium instance. Simply put: if it looks good in your browser, it will look exactly the same in your PDF document. This means we get out-of-the-box support for modern web standards like CSS Grid, Flexbox, and advanced typography — things that traditional PDF generators struggle with immensely.</li></ul><p><strong>Why We Need Queues</strong></p><p>If you’ve ever tried generating a PDF synchronously during an active Node.js HTTP request, you’ve likely felt the pain. Node.js runs on a single-threaded Event Loop.</p><p>When Puppeteer spins up a headless browser, renders HTML, fetches remote assets (like images or stylesheets), and prints to PDF, it’s a heavily CPU and memory-intensive process. If you allow multiple users to request PDFs simultaneously without a queue system:</p><p>1. <strong>The Event Loop blocks:</strong> Other users’ API requests will hang while the CPU finishes painting the PDF.</p><p>2. <strong>Resource Exhaustion:</strong> Your server RAM will spike as multiple Chromium instances fire up simultaneously, inevitably leading to an Out of Memory (OOM) crash.</p><p>3. <strong>Zombie Processes:</strong> Unhandled timeouts can leave orphaned browser instances running in the background.</p><p>By introducing <strong>Redis</strong> and <strong>BullMQ</strong> (a robust message queue system for NestJS), we solve these issues at the architectural level. When a user requests a report, the backend instantly responds with a `jobId`, while a background worker processes the PDF asynchronously. This pattern allows us to cleanly throttle concurrency — for example, only allowing 3 PDFs to be generated simultaneously, regardless of whether 100 users clicked “Export” at once.</p><p><strong>Technical Challenges &amp; Implementation</strong></p><p><strong>1. Managing the Queue with NestJS</strong></p><p>NestJS provides a seamless, declarative wrapper around BullMQ. We can easily define a queue and dispatch jobs without muddying our controller logic.</p><pre>/ pdf.controller.ts<br>import { Controller, Post, Body } from &#39;@nestjs/common&#39;;<br>import { InjectQueue } from &#39;@nestjs/bullmq&#39;;<br>import { Queue } from &#39;bullmq&#39;;<br><br>@Controller(&#39;reports&#39;)<br>export class ReportsController {<br>  constructor(@InjectQueue(&#39;pdf-generation&#39;) private pdfQueue: Queue) {}<br><br>  @Post(&#39;generate&#39;)<br>  async generateReport(@Body() data: any) {<br>    // Dispatch the job to the Redis queue instead of processing synchronously<br>    const job = await this.pdfQueue.add(&#39;generate-invoice&#39;, data);<br>    <br>    return { <br>      message: &#39;PDF generation has been queued successfully&#39;, <br>      jobId: job.id <br>    };<br>  }<br>}</pre><p><strong>2. The Background Worker (Consumer)</strong></p><p>The consumer worker is an isolated process that listens to the Redis queue, picks up jobs, and handles the brittle Puppeteer logic. If the job fails (e.g., a network timeout while fetching an external logo), BullMQ can automatically retry it without any user intervention.</p><pre>// pdf.processor.ts<br>import { Processor, WorkerHost } from &#39;@nestjs/bullmq&#39;;<br>import { Job } from &#39;bullmq&#39;;<br>import * as puppeteer from &#39;puppeteer&#39;;<br><br>@Processor(&#39;pdf-generation&#39;)<br>export class PdfProcessor extends WorkerHost {<br>  async process(job: Job&lt;any, any, string&gt;): Promise&lt;any&gt; {<br>    const { htmlContent } = job.data;<br>    <br>    // Launch headless browser (Tip: reuse a browser pool in production!)<br>    const browser = await puppeteer.launch({ <br>      headless: true,<br>      args: [&#39;--no-sandbox&#39;, &#39;--disable-setuid-sandbox&#39;] <br>    });<br>    <br>    const page = await browser.newPage();<br>    <br>    // Load our React-generated HTML<br>    await page.setContent(htmlContent, { waitUntil: &#39;networkidle0&#39; });<br>    <br>    const pdfBuffer = await page.pdf({<br>      format: &#39;A4&#39;,<br>      printBackground: true,<br>      margin: { top: &#39;20px&#39;, bottom: &#39;20px&#39; }<br>    });<br>    <br>    await browser.close();<br>    <br>    // In a real-world scenario, you&#39;d upload this buffer to S3 or a DB here<br>    return { status: &#39;completed&#39;, path: `/downloads/${job.id}.pdf` };<br>  }<br>}</pre><p><strong>3. Bridging React to Node</strong></p><p>We compile React on the server to get clean htmlContent to feed into Puppeteer.</p><pre>// template-renderer.tsx<br>import * as React from &#39;react&#39;;<br>import { renderToStaticMarkup } from &#39;react-dom/server&#39;;<br><br>// Standard React Component<br>const InvoiceTemplate = ({ customerName, totalAmount }) =&gt; (<br>  &lt;div style={{ padding: &#39;40px&#39;, fontFamily: &#39;Inter, sans-serif&#39; }}&gt;<br>    &lt;h1&gt;Invoice for {customerName}&lt;/h1&gt;<br>    &lt;div style={{ display: &#39;flex&#39;, justifyContent: &#39;space-between&#39; }}&gt;<br>      &lt;p&gt;Total Due:&lt;/p&gt;<br>      &lt;strong&gt;${totalAmount}&lt;/strong&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>);<br><br>export const generateHtmlString = (data: any): string =&gt; {<br>  // Converts the React tree to a raw HTML string for Puppeteer<br>  return renderToStaticMarkup(&lt;InvoiceTemplate {...data} /&gt;);<br>};</pre><p>By adopting this strategy, we keep our presentation logic completely decoupled from our PDF rendering pipeline.</p><p><strong>Bringing It to Life: The Frontend Playground</strong></p><p>Building a robust backend is only half the battle; we need a way to interact with it and validate the user experience. The frontend directory in the repository provides a clean, minimalistic React application designed specifically to test our asynchronous PDF generation flow.</p><p>When dealing with background jobs, the traditional request-response cycle changes. The user can’t just click “Download” and wait with a spinning cursor while the server sweats over generating the file. The frontend elegantly handles this new asynchronous reality:</p><p>1. <strong>The Request:</strong> When you click “Generate Report,” the frontend sends the payload to our NestJS API.</p><p>2. <strong>The Handshake:</strong> Instead of a file, the API immediately returns a `jobId`.</p><p>3. <strong>The Waiting Game (Polling):</strong> The frontend enters a loading state and begins polling a status endpoint (e.g., `/reports/status/:jobId`) every few seconds.</p><p>4. <strong>The Delivery:</strong> Once the backend worker flags the job as completed, the frontend receives the final download URL and automatically triggers the file download for the user.</p><p>Here is a simplified look at how that logic is handled in the React frontend:</p><pre>// A simplified custom hook for handling the async PDF generation<br>const usePdfGenerator = () =&gt; {<br>  const [isGenerating, setIsGenerating] = useState(false);<br><br>  const generateAndDownload = async (data) =&gt; {<br>    setIsGenerating(true);<br>    <br>    try {<br>      // 1. Dispatch the job<br>      const response = await api.post(&#39;/reports/generate&#39;, data);<br>      const { jobId } = response.data;<br>      <br>      // 2. Poll for completion<br>      const checkStatus = setInterval(async () =&gt; {<br>        const statusRes = await api.get(`/reports/status/${jobId}`);<br>        <br>        if (statusRes.data.status === &#39;completed&#39;) {<br>          clearInterval(checkStatus);<br>          setIsGenerating(false);<br>          <br>          // 3. Trigger the download<br>          window.open(statusRes.data.downloadUrl, &#39;_blank&#39;);<br>        }<br>      }, 2000); // Check every 2 seconds<br>      <br>    } catch (error) {<br>      console.error(&#39;Failed to generate PDF&#39;, error);<br>      setIsGenerating(false);<br>    }<br>  };<br><br>  return { generateAndDownload, isGenerating };<br>};</pre><p>To test it yourself, simply spin up the application using the provided `docker-compose` setup, navigate to the frontend running on your localhost, and watch the magic happen!</p><p><strong>Proving the Architecture: Stress Testing with Artillery</strong></p><p>We claimed earlier that our Redis + BullMQ architecture prevents Node.js from crashing under heavy load. But in software engineering, we don’t just make claims — we prove them.</p><p>To validate our system, we use `Artillery`, a modern, powerful load-testing toolkit. Artillery allows us to simulate sudden spikes in traffic, mimicking a scenario where hundreds of users request complex PDF reports at the exact same time.</p><p>If we ran this test against a synchronous Puppeteer setup, the server’s RAM would skyrocket, the CPU would peg at 100%, and Node.js would inevitably crash with an OOM (Out of Memory) error.</p><p>With our queued architecture, the results are entirely different. Here is a look at a typical Artillery configuration file (load-test.yml) we use to hammer the system:</p><pre>config:<br>  target: &quot;http://localhost:3000&quot;<br>  phases:<br>    - duration: 60       # Run the test for 60 seconds<br>      arrivalRate: 10    # 10 new virtual users per second<br>      name: &quot;Sustained load&quot;<br>  payload:<br>    # We can feed realistic dummy data to our endpoints<br>    path: &quot;test-data.csv&quot;<br>    fields:<br>      - &quot;customerName&quot;<br>      - &quot;totalAmount&quot;<br><br>scenarios:<br>  - name: &quot;Generate PDF Flow&quot;<br>    flow:<br>      - post:<br>          url: &quot;/reports/generate&quot;<br>          json:<br>            customerName: &quot;{{ customerName }}&quot;<br>            totalAmount: &quot;{{ totalAmount }}&quot;<br>          capture:<br>            - json: &quot;$.jobId&quot;<br>              as: &quot;jobId&quot;<br>      # We can even script Artillery to poll the status endpoint <br>      # just like our frontend does!<br>      - loop:<br>          - get:<br>              url: &quot;/reports/status/{{ jobId }}&quot;<br>          - think: 2 # wait 2 seconds between checks<br>        whileTrue: &quot;status !== &#39;completed&#39;&quot;</pre><p><strong>The Results:</strong></p><p>When running this Artillery script against our NestJS application, the API response times remain incredibly fast (usually in the low milliseconds). The main thread is never blocked. Our BullMQ workers steadily churn through the Redis queue in the background, generating PDFs at a controlled concurrency limit (e.g., 5 at a time).</p><p>It’s the ultimate proof that our architectural choices work. The system degrades gracefully by extending the wait time for the user, rather than crashing the server and taking the entire application offline.</p><p><strong>Future Directions: The Enterprise Architecture (Scaling to 1,000 PDFs/Second)</strong></p><p>Our current setup — NestJS, Redis, and a background worker — is incredibly resilient and will easily handle the reporting needs of most small to medium applications. But what happens if your app goes viral, or you land a massive enterprise contract, and suddenly you need to generate <strong>1,000 complex PDFs per second</strong>?</p><p>If you try to scale our current implementation vertically (buying a bigger, beefier server), you will quickly hit a physical ceiling. Puppeteer is notoriously CPU and Memory hungry. Even the most expensive cloud instance will eventually choke under the weight of thousands of concurrent Chromium processes.</p><p>To handle enterprise-scale throughput, we must evolve our system into a distributed, horizontally scaled architecture:</p><p>1. <strong>Decoupling the Fleet (API vs. Workers):</strong> Right now, our NestJS API and our BullMQ worker might live in the same codebase. At scale, these must be split. The API Nodes become lightweight, horizontally scaled instances that just push jobs to Redis. The Worker Nodes become heavy-duty instances that solely listen to Redis and render PDFs.</p><p>2. <strong>Event-Driven Auto-Scaling (KEDA):</strong> By deploying our Worker Nodes to a Kubernetes cluster, we can introduce KEDA. Instead of scaling based on CPU usage, KEDA watches the length of our Redis queue. If the queue hits 10,000 pending jobs, it instantly spins up hundreds of new Worker pods to chew through the backlog, then kills them to save costs when the queue is empty.</p><p>3. <strong>Outsourcing the Browser Fleet:</strong> Managing a fleet of headless Chromium instances in Docker is painful. At massive scale, you separate the Node.js worker logic from the browser execution. Instead of puppeteer.launch(), you use puppeteer.connect() to route rendering instructions over WebSockets to a dedicated, highly optimized browser grid (like Browserless.io or a serverless cluster).</p><p>4. <strong>Streaming to Cloud Storage:</strong> Generating 1,000 PDFs per second produces gigabytes of data. Instead of holding buffers in memory, the worker should stream the generated PDF directly to an S3 bucket using a multipart upload, then simply notify the client with a pre-signed download URL.</p><p><strong>Engineering for Reality</strong></p><p>In real-world software engineering, the best solutions aren’t just about writing code that works on localhost; they’re about building systems that let you sleep at night when production traffic spikes.</p><p>We started with a simple problem — generating a PDF — and solved it by embracing decoupling, asynchronous processing, and horizontal scalability. By offloading the presentation logic to React, the rendering to Puppeteer, and the orchestration to Redis and NestJS, we’ve built an architecture that degrades gracefully instead of failing catastrophically.</p><p>Whether you’re exporting a single monthly invoice or generating thousands of compliance reports an hour, this pattern provides a rock-solid foundation you can rely on.</p><p>You can find the complete source code, the Docker configurations, and the Artillery load-testing scripts in the <a href="https://github.com/kterto/pdf-generator-nest">https://github.com/kterto/pdf-generator-nest</a> GitHub Repository. Feel free to clone it, poke around the architecture, and adapt it for your own projects.</p><p>Happy coding, and may your event loops never block! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87dbd7eb2118" width="1" height="1" alt=""><hr><p><a href="https://medium.com/capyba/building-a-pdf-report-generator-with-react-puppeteer-nestjs-and-redis-87dbd7eb2118">Building a PDF Report Generator with React, Puppeteer, NestJS, and Redis</a> was originally published in <a href="https://medium.com/capyba">Capyba</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter as a tool to establish Design & Development Cooperation Common Ground]]></title>
            <link>https://medium.com/capyba/flutter-as-a-tool-to-establish-design-development-cooperation-common-ground-5f346f5d8a9b?source=rss-2d42e00bd33e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f346f5d8a9b</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[ui-ux]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[splash-screen]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Kainã Terto Pereira]]></dc:creator>
            <pubDate>Thu, 06 Jun 2024 15:50:50 GMT</pubDate>
            <atom:updated>2024-06-06T15:50:50.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HZiprrfylAIzIZ5PsR9lIQ.png" /></figure><h4>Abstract</h4><p>In a lot of different areas there is a false conflict between people who design things and people in charge of building things, and in my experience, software development is not different from other areas like construction or industry. Meaning that people who are meant to work together, like UI/UX designers and software developers, are more frequently than they should, spending energy not cooperating with each other and arguing about the feasibility of features. Although, there is some reason for the arguing, I mean, spending too much time building a software might determine the viability of that product; there is no reason why these two ends couldn’t find a common ground to produce a system visually appealing, functional and aiming for the best user experience potential it has.</p><p>With the evolution of the ecosystem of frameworks that help to achieve that goal of producing the best possible software in terms of UI/UX, we point out that one of the best frameworks to create that common ground required for optimal cooperation between design and development teams is Flutter. Flutter is nearly a sandbox where one, with less effort than any known hybrid framework, can produce the largest range of different UIs. So, instead of trying to argue conceptually about why we believe Flutter is a good tool to bring design and development teams together, we`ve decided to try and show it by experimenting with the implementation of a proof of concept.</p><h4>What are we going to implement?</h4><p>The usage of an introductory screen where the app can fetch data from backend, evaluate auth state, or any other custom task needed to load and get things up and running; have never been so common. It is usually named as Splash screen, It presents a chance to build your brand identity, deliver some cool marketing campaigns, etc, possibilities are numerous! It means that you need to keep the app user occupied while all those things are happening. One option to achieve this is to use a static screen, with your brand logo, colors, maybe name, something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*rEL-esLvySHhcpRA2GD-7Q.png" /><figcaption>static SplashScreen</figcaption></figure><pre>class CapybaDaySplashScreen extends StatelessWidget {<br>  const CapybaDaySplashScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      backgroundColor: ColorTokens.capybaPurple,<br>      body: Center(<br>        child: Stack(<br>          children: [<br>            const SizedBox(<br>              height: 113,<br>              width: 208,<br>            ),<br>            Row(<br>              mainAxisAlignment: MainAxisAlignment.center,<br>              crossAxisAlignment: CrossAxisAlignment.end,<br>              mainAxisSize: MainAxisSize.min,<br>              children: [<br>                Image.asset(<br>                  CapybaDayTwentyThreeTestImages.capyba,<br>                  width: 183,<br>                  height: 48,<br>                ),<br>                const SizedBox(width: 8),<br>                Column(<br>                  mainAxisSize: MainAxisSize.min,<br>                  children: [<br>                    Image.asset(<br>                      CapybaDayTwentyThreeTestImages.twentyThree,<br>                      width: 117,<br>                      height: 57,<br>                    ),<br>                    const SizedBox(height: 9),<br>                  ],<br>                ),<br>              ],<br>            ),<br>            Positioned(<br>              right: 0,<br>              child: Stack(<br>                alignment: Alignment.center,<br>                children: [<br>                  const SizedBox(height: 113, width: 117),<br>                  Positioned(<br>                    top: 21,<br>                    child: Image.asset(<br>                      CapybaDayTwentyThreeTestImages.capivara,<br>                      width: 88,<br>                      height: 92,<br>                    ),<br>                  ),<br>                ],<br>              ),<br>            ),<br>            Positioned(<br>              right: 18,<br>              bottom: 4.57,<br>              child: Stack(<br>                alignment: Alignment.bottomLeft,<br>                children: [<br>                  const SizedBox(width: 170, height: 87.4),<br>                  Image.asset(<br>                    CapybaDayTwentyThreeTestImages.day,<br>                    height: 48.8,<br>                    width: 100.9,<br>                  ),<br>                ],<br>              ),<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>That would probably do the job, and in most cases should work. And usually, with a project already set, you should be able to build such a screen in about 1h. But sometimes we need to add some motion to things to focus on what matters, like your brand logo, or even to produce a more fluid user experience, distracting the user from the time spent on this step. Well, if the technical difficulties to implement such an animated solution are too time consuming, any manager would probably cut corners at this point and say that it is too expensive, that it doesn’t pay off, and he/she would probably be making the right call. That would produce at least two possible outcomes. On one hand, the developer side would be probably relieved to not have to spend many hours just producing the correct ui, on the other hand, the design team would probably get frustrated to not having a great solution been implemented because of technical difficulties beyond their reach. (at least, my projection of those two personas would feel like I described). In the long run, this kind of friction could cause the conflict described in the abstract. So let’s try to create such an animated screen, using just some assets and Flutter’s native implicit animations, showcasing the point defended here: UI/UX matters, and we can produce a lot of cool stuff using Flutter with minimum efford.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*Rrd4t3ZxvcjwqOLTTxCi8g.gif" /><figcaption>animated SplashScreen</figcaption></figure><h4>Staggered Animations</h4><p>To implement the animation proposed for this splash screen by our Designer Mage José Gervásio, we will use a concept described in <a href="https://docs.flutter.dev/ui/animations/staggered-animations">Flutter’s official documentation</a>: Staggered Animations. Quoting the documentations: “Staggered animations are a straightforward concept: visual changes happen as a series of operations, rather than all at once”. The common pattern used to implement those kinds of animations is to have a <strong>StatefulWidget</strong> (or a HookWidget if you’re into FlutterHooks, which I highly recommend if you don’t know or use yet!) that provides one <strong>AnimationController</strong> and orchestrates all the animation objects presented in another widget, this one Stateless. Each animation object defined in the <strong>StatelessWidget </strong>specifies an animation during an <strong>Interval, </strong>and each property being animated would create a <strong>Tween </strong>(funny name chosen by the Flutter team to refer to be<strong>Tween</strong>).</p><h4>Implementing</h4><p>We can divide implementation in three steps. In the first step, we have colorful stripes changing size giving this sense of motion, and it takes, say, 35% of the total animation time. In this step we have first a gray frame that starts to shrink, and after some time, two stripes, one pink and another yellow, start expanding, and at some point a purple container starts showing and it will become the background of the endscreen. In the second step, that starts at around 20% of animation duration (it means that there is overlap, that is quite simple to control, as we’ll see), our sharming Capybara mage shows, changing slightly its vertical position. And finally, in the third step, two things happen simultaneously, our Capybara mage shrinks and animates its position to stop at its desired position at the final splash image, and the other elements, Fadein and slides to its final position. <br>We can see in the diagram below the intervals described:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*XSNvEAI-rag81ccKaEXG7Q.png" /><figcaption>Animations interval diagram</figcaption></figure><p>We could have a StatefulWidget like this:</p><pre>class CapybaDayAnimatedSplashScreen extends StatefulWidget {<br>  const CapybaDayAnimatedSplashScreen({super.key});<br><br>  @override<br>  State&lt;CapybaDayAnimatedSplashScreen&gt; createState() =&gt;<br>      _CapybaDayAnimatedSplashScreeState();<br>}<br><br>class _CapybaDayAnimatedSplashScreeState<br>    extends State&lt;CapybaDayAnimatedSplashScreen&gt; with TickerProviderStateMixin {<br>  late AnimationController _controller;<br><br>  @override<br>  void initState() {<br>    super.initState();<br><br>    _controller = AnimationController(<br>      vsync: this,<br>      duration: const Duration(milliseconds: 3000),<br>    );<br>    Future.delayed(const Duration(milliseconds: 300))<br>        .then((value) =&gt; _controller.forward());<br>  }<br><br>  @override<br>  void dispose() {<br>    super.dispose();<br>    _controller.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return SplashStaggeredAnimation(<br>      controller: _controller.view,<br>      viewportSize: MediaQuery.of(context).size,<br>    );<br>  }<br>}</pre><p>The proposed duration for the whole animation is 3 seconds and it’s set to start 300 milliseconds after the screen is shown.</p><p>And the <strong>StatelessWidget </strong>that will produce the desired animation is shown below:</p><pre>class SplashStaggeredAnimation extends StatelessWidget {<br>  SplashStaggeredAnimation({<br>    super.key,<br>    required this.controller,<br>    required this.viewportSize,<br>  })  : grayHeight =<br>            Tween&lt;double&gt;(begin: viewportSize.height, end: 0.0).animate(<br>          CurvedAnimation(<br>            parent: controller,<br>            curve: const Interval(<br>              0.0,<br>              0.250,<br>              curve: Curves.easeInOutQuad,<br>            ),<br>          ),<br>        ),<br>        purpleHeight =<br>            Tween&lt;double&gt;(begin: 0, end: viewportSize.height).animate(<br>          CurvedAnimation(<br>            parent: controller,<br>            curve: const Interval(<br>              0.150,<br>              0.350,<br>              curve: Curves.easeOutSine,<br>            ),<br>          ),<br>        ),<br>        capybaraPadding = EdgeInsetsTween(<br>          begin: const EdgeInsets.only(top: 48),<br>          end: EdgeInsets.zero,<br>        ).animate(<br>          CurvedAnimation(<br>            parent: controller,<br>            curve: const Interval(<br>              0.200,<br>              0.350,<br>              curve: Curves.easeOutSine,<br>            ),<br>          ),<br>        ),<br>        staticStackOpacity = Tween&lt;double&gt;(<br>          begin: 0.0,<br>          end: 1.0,<br>        ).animate(<br>          CurvedAnimation(<br>            parent: controller,<br>            curve: const Interval(<br>              0.720,<br>              0.950,<br>              curve: Curves.ease,<br>            ),<br>          ),<br>        ),<br>        staticStackPadding = EdgeInsetsTween(<br>          begin: const EdgeInsets.only(top: 100),<br>          end: EdgeInsets.zero,<br>        ).animate(<br>          CurvedAnimation(<br>            parent: controller,<br>            curve: const Interval(<br>              0.720,<br>              0.950,<br>              curve: Curves.ease,<br>            ),<br>          ),<br>        ),<br>        capybaraSizeFactor = Tween&lt;double&gt;(<br>          begin: 1.0,<br>          end: 0.48,<br>        ).animate(<br>          CurvedAnimation(<br>            parent: controller,<br>            curve: const Interval(<br>              0.700,<br>              1.000,<br>              curve: Curves.ease,<br>            ),<br>          ),<br>        ),<br>        capybaraFinalHorizontalPosition = Tween&lt;double&gt;(<br>          begin: 61.8,<br>          end: 17.3,<br>        ).animate(<br>          CurvedAnimation(<br>            parent: controller,<br>            curve: const Interval(<br>              0.700,<br>              1.000,<br>              curve: Curves.ease,<br>            ),<br>          ),<br>        ),<br>        capybaraFinalVerticalPosition = Tween&lt;double&gt;(<br>          begin: (viewportSize.height - 192.7) / 2,<br>          end: (viewportSize.height - (192.7 - 122)) / 2,<br>        ).animate(<br>          CurvedAnimation(<br>            parent: controller,<br>            curve: const Interval(<br>              0.700,<br>              1.000,<br>              curve: Curves.ease,<br>            ),<br>          ),<br>        );<br><br>  final Animation&lt;double&gt; controller;<br>  final Size viewportSize;<br>  final Animation&lt;double&gt; grayHeight;<br>  final Animation&lt;double&gt; purpleHeight;<br>  final Animation&lt;EdgeInsets&gt; capybaraPadding;<br>  final Animation&lt;double&gt; staticStackOpacity;<br>  final Animation&lt;EdgeInsets&gt; staticStackPadding;<br>  final Animation&lt;double&gt; capybaraSizeFactor;<br>  final Animation&lt;double&gt; capybaraFinalHorizontalPosition;<br>  final Animation&lt;double&gt; capybaraFinalVerticalPosition;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return AnimatedBuilder(animation: controller, builder: _buildAnimation);<br>  }<br><br>  Widget _buildAnimation(BuildContext context, Widget? child) {<br>    return Stack(<br>      children: [<br>        Container(<br>          height: viewportSize.height,<br>          width: viewportSize.width,<br>          color: ColorTokens.capybaPurple,<br>          child: Stack(<br>            alignment: Alignment.center,<br>            children: [<br>              Opacity(<br>                opacity: staticStackOpacity.value,<br>                child: Padding(<br>                  padding: staticStackPadding.value,<br>                  child: const SplashStaticStack(withCapybara: false),<br>                ),<br>              ),<br>              SizedBox(<br>                width: 308,<br>                child: Stack(<br>                  alignment: Alignment.center,<br>                  children: [<br>                    Positioned(<br>                      right: capybaraFinalHorizontalPosition.value,<br>                      top: capybaraFinalVerticalPosition.value,<br>                      child: Visibility(<br>                        visible: controller.value &gt; 0.20,<br>                        child: Center(<br>                          child: Padding(<br>                            padding: capybaraPadding.value,<br>                            child: Image.asset(<br>                              CapybaDayTwentyThreeTestImages.capivara,<br>                              width: 184.4 * capybaraSizeFactor.value,<br>                              height: 191.7 * capybaraSizeFactor.value,<br>                            ),<br>                          ),<br>                        ),<br>                      ),<br>                    ),<br>                  ],<br>                ),<br>              ),<br>            ],<br>          ),<br>        ),<br>        Column(<br>          children: [<br>            Container(<br>              width: viewportSize.width,<br>              height: grayHeight.value,<br>              color: ColorTokens.capybaGray,<br>            ),<br>            Expanded(<br>              child: Container(<br>                width: viewportSize.width,<br>                color: ColorTokens.capybaPink,<br>              ),<br>            ),<br>            Expanded(<br>              child: Container(<br>                width: viewportSize.width,<br>                color: ColorTokens.capybaYellow,<br>              ),<br>            ),<br>            Container(<br>              width: viewportSize.width,<br>              height: purpleHeight.value,<br>              color: Colors.transparent,<br>            ),<br>          ],<br>        ),<br>      ],<br>    );<br>  }<br>}</pre><p>As it can be seen, a complex outcome can be achieved with a relatively simple code. With proficiency, a developer can produce this in one or two hours.</p><h4>Comparison</h4><p>Comparing the difficulty of implementing both examples presented here, one can say that although the animated version is a bit more complex, it didn’t take that much time to implement. To understand how it could benefit the feeling of the end-user, I’ve run a pool to evaluate the aesthetics and general feel. Far from being a valid robust statistics but serving as a piece of evidence, it points out that choosing the animated version could represent a real improvement in general app perception.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*EuG1uebssbS_McLpChj-IA.png" /><figcaption>Overall grade of static SplashScreen</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*tSR4HWDe_BGVBPL1zYpfcA.png" /><figcaption>Overall grade of animated SplashScreen</figcaption></figure><p>Static version averaged to 7.7 while the animated version averaged to 9.7 on a 0–10 scale. (I know, I know… There are just to few votes to build a real statistics, but I think that it points the main perception).</p><h4>Conclusion</h4><p>With Flutter as a tool, we can bring together developers and designers to discuss real value to the product they work to build. The decisions made in real projects must consider all the resources available, and evaluate the real value a particular design might actually add to the final product. The point is that, with some proficiency, the developers will not talk about the feasibility of designs blindsighted, and the decision can be made in a more balanced way.</p><p>I would like to dedicate a special thank you to our designer José Gervásio for proposing such an amazing design that was pretty fun to implement.</p><p>This project was implemented as part of the Capyba Day 2023, live coded in about 1h!. The final code is available in the <a href="https://github.com/CapybaHub/capyba_day_xxiii">github repository</a>. Any suggestions and improvements please, be my guest and leave a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f346f5d8a9b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/capyba/flutter-as-a-tool-to-establish-design-development-cooperation-common-ground-5f346f5d8a9b">Flutter as a tool to establish Design &amp; Development Cooperation Common Ground</a> was originally published in <a href="https://medium.com/capyba">Capyba</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Flutter environments. The Capyba’s way]]></title>
            <link>https://medium.com/capyba/setting-flutter-environments-the-capybas-way-cb7d085b3b74?source=rss-2d42e00bd33e------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb7d085b3b74</guid>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Kainã Terto Pereira]]></dc:creator>
            <pubDate>Fri, 04 Nov 2022 18:53:18 GMT</pubDate>
            <atom:updated>2022-11-04T18:53:18.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*_J1ro2AjqsuG9Y8O.jpeg" /></figure><h3>Introduction</h3><p>Once developing pet projects or POCs, one might want to quickly see things working and actually cut some corners when it comes to real life project structure. One particular thing that always comes to mind while starting a new real life project is environment differentiation. Environment differentiation is paramount, in terms of real life development. On one hand, no one wants to develop a new system connected to the production environment and possibly mess the database up; on the other hand, having different environments (i.e. dev, staging, production) might speed integration of new features between backend and client systems, or even it might produce the desired flexibility over the workflow and deployment cycles (i.e. developing new feature locally in dev environment, then deploy it to a staging or qa environment for further testing the integration and that everything works well before actually delivering it to production).</p><p>In specific, Flutter has a way of mapping android flavors and ios schemes to produce the desired build variants covering the different environments, and that is at most ok. Here in Capyba, we’ve always felt like something was missing, and over and over we’ve been repeating some manual tasks in order to properly achieve the desired distinction of environments when developing real life Flutter projects. As we use Flutter for Android and Ios development, the aim of this article is to summarize and standardize these manual tasks done explicitly on Android and Ios, so it can serve as future reference for our company, and hopefully for other companies and solo developers that might as well, face the same challenges when developing Flutter projects.</p><h3>Our requirements</h3><p>To avoid misleading running apps that do not properly point out the current environment or do not properly connect to its corresponding specific services, we’ve come up with a list of requirements that must be met by all our Flutter/mobile projects.</p><p>Namely, different environments should produce apps with:</p><ol><li>Different bundle/application ids so that multiple instances of the app pointing to different environments could be installed at the same time.</li><li>Different app launcher icons and different display names, so that they are seamlessly distinguishable from each other.</li><li>By default Flutter builds apps with a Banner at the top right corner to identify debug builds, adding on that, we’ve decided to have a Banner at the top left corner with the name of the environment, in case of running the app in an environment other than production, or with ‘ENVLESS’ when no environment is yet set.</li><li>If the app communicates with some specific service (i.e. Firebase services), every environment should be configured separately on its own (i.e. firebase project).</li><li>Environment variables should be placed on .env files that shouldn’t be kept in version control, in order to maintain a semantic equivalence of environment variables treatment of other technologies.</li></ol><p>Requirements from 1 to 3, are the easy ones, although configuration for Android and Ios have different approaches, as we are going to see shortly, these requirements can be met in a straightforward way. On the other hand, requirements 4 and 5, needed some additional steps that we are going to describe too.</p><p>For the sake of concreteness we will from now on consider three environments: dev, staging and production, and proceed step-by-step in the configuration first on Android, and then on iOS and Flutter.</p><p>It is important to make a disclaimer here: specially on Android, it is possible to do things in different ways, and the aim here, rather than showing a unique form or the best form, is to present ONE form of accomplish the desired requirements. Now, let’s move on to the setup.</p><h3>Android Setup</h3><ol><li>Let’s go to app module <em>build.gradle -&gt;</em> <strong>android/app/gradle, </strong>and add definition of property <em>flavorDimensions</em>, here we will use only “default”, and then add definition of <em>productFlavors</em> property setting for each environment a property with fields <em>dimension</em> “default”, and we will add a <em>applicationIdSuffix</em> with the name of the environment (for all but production environment) to produce the desired different application ids. Things should look like this:</li></ol><pre>…<br>defaultConfiguration {<br>     applicationId &quot;com.capyba.example&quot;<br> …<br>}flavorDimensions &quot;default&quot;<br>productFlavors {<br>     dev {<br>         dimension &quot;default&quot;<br>         applicationIdSuffix &quot;.dev&quot;<br>     }<br>     staging {<br>         dimension &quot;default&quot;<br>         applicationIdSuffix &quot;.staging&quot;<br>     }<br>     production {<br>         dimension &quot;default&quot;<br>     }<br>}</pre><p>2. Afterwards, let’s create a folder for each environment (all but production environment) at <strong>android/app/src/</strong>, like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/0*5loCyK6Vj7DxxA06" /></figure><p>3. Now, as we’ve proposed, we need to generate data for the dev and staging launcher icons. One easy way of doing this is using AndroidStudio. Let’s open the project’s android folder on AndroidStudio. Now, after project syncing, change view from Android to Project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/0*FgBMJfWvy-y-fSRu" /></figure><p>Then, go to one of env folders created in the last step and right click on it, selecting <strong>New-&gt;Image Asset, </strong>like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/0*PDmcdaMG0R31s9WA" /></figure><p>4. A window will prompt so that one can select the path for the icon related to the selected environment, and name it with the same name of the mipmap on the <em>main/module/res</em><strong> </strong>folder, in the example the name is the default <em>ic_launcher </em>:</p><p>the prompted window is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*ClZAOUfWVBLQxV7w" /></figure><p>Hit next button and then choose the res folder of the correspondent environment as destination, in the example, staging, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*o6extIg6tuIXHE0u" /></figure><p>5. repeat steps 3 and 4 for every environment</p><p>6. Now, let’s add a <em>strings</em> resources file to the environment being configured folder. First right-click on the res folder and select <strong>New-&gt;android resource file, </strong>give it a name, for instance, <em>strings.xml </em>and add a resource string named, for example, <em>app-display-name, </em>(the particular chosen name is not relevant here). Repeat it for every desired environment,( even for production/main module this time)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/0*11lcOyjYoxVMmEhk" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*-xzDqTKufhQLTs_h" /></figure><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;resources&gt;<br>     &lt;string name=&quot;app_display_name&quot;&gt;Capyba&#39;s Example Dev&lt;/string&gt;<br>&lt;/resources&gt;</pre><p>7. Now, we just have to pass this string resource to the <em>label </em>parameter at main module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/0*UmZnjiUCfk5zTw5q" /></figure><p>Now, I’ve completed requirement 2 for android, and we might continue just skipping for now, Flutter configuration, as we are going to let this part to the end.</p><p>And for now, we have three different apps, with custom launcher icons and names that could be installed at the same time on the same Android device, one for each environment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*izyTBV4d7C82c946.png" /></figure><h3>IOs setup</h3><p>Now, let’s replicate the same results on IOs, (unfortunately, this can be accomplished only using a macOS machine). Let’s start opening the <strong><em>ios/</em></strong> subfolder of the project using xcode.</p><ol><li>Click on <strong>Runner (on the right of the source control) -&gt; New Scheme.</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/0*xfyVuFipGODjfc6l" /></figure><p>2. Add the desired schemes, one for each environment. i.e.: dev, staging, (like on android we will reserve the default scheme for production environment.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/0*b32HgcotPg_nTfCs" /></figure><p>3. Go to <strong>Runner -&gt; Manage Schemes </strong>and rename the default Runner scheme to production</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/0*Bqem-QmCNmGh7dK1" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*YeMdri8enZgDGUTB" /></figure><p>4. In the project structure pane, select <strong>Runner</strong>, then select <strong>Project-&gt;Runner, </strong>then in tab <strong>info</strong>, select <strong>debug configuration</strong> and click on the <strong>plus icon</strong>, then select <strong>Duplicate Debug Configuration</strong>, and rename the copy to <strong>Debug-dev. </strong>Repeat it for <strong>Release</strong> and <strong>Profile</strong> configurations. And then, repeat the same steps for the other environments other than production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*QdkMQMO8lIoM4xfR" /></figure><p>5. Rename the <strong>Release, Profile and Debug </strong>configurations to <strong>Release-production, Profile-production and Debug-production, </strong>and that’s the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*s4kQu12pMPrItSzQ" /></figure><p>6. Now, go back to manage schemes and connect the build configuration with the correct to each environment (repeat for each environment/scheme):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*4XLvu09f-6yWTrOe" /></figure><p>7. Now, go to <strong>Runner </strong>target, and then to <strong>Build Settings-&gt;Packaging-&gt;Product Bundle identifier. </strong>Here we can give a bundle Identifier for each build configuration. For envs, other than <strong>production</strong>, we are going to add a suffix to the package bundle identifier, i.e: <strong>production: </strong><em>com.capyba.example, </em><strong>dev: </strong><em>com.capyba.example.dev </em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*0aeZUBokgSJFFkLU" /></figure><p>after renaming:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/0*bBqZOOtJomC8Ey6j" /></figure><p>8. Let’s add <strong>User-Defined Settings</strong> and create <strong>DISPLAY_NAME, </strong>and set a name for each build variant:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*svXz76jG_KWAeIpi" /></figure><p>create <strong>DISPLAY_NAME:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/0*H4mP6QGGQ8ptkOWz" /></figure><p>Add values to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/0*2BK8jSBdJW7qZdv-" /></figure><p>9. Connect the <strong>DISPLAY_NAME</strong>, with the option in the info tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*TaGBb-eN4Zm1qIZc" /></figure><p>10. Now, let’s add assets for each appLauncher and connect it to each scheme. Go to <strong>Runner-&gt;Runner-&gt;Assets </strong>on the project structure pane, and then, hit the <strong>plus icon-&gt;ios-&gt;ios appIcon:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/0*c2XcWlSlr9to_-p9" /></figure><p>and after adding assets for each scheme, let’s connect them to each scheme. Go back to <strong>Runner </strong>target, and then to <strong>Build Settings-&gt;Primary App Icon set name, </strong>and choose the correct icon for each scheme:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*8qBer7irYxpdwq4T" /></figure><p>And now I’ve accomplished the same two requirements for Ios, and we have now, three different installable apps with, different Display names, and app icons:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*J3yvYTLbmKGLEBCI.png" /></figure><h3>Flutter setup</h3><p>To accomplish what we want in terms of in app differentiation, we are going to use <em>–dart-define </em>to pass values on compile time to code and then use them. In order to automate the process we’ve decided to write a Makefile, and add some shell scripting to the process, this way, we’ve come up with a setup where we have .env.dev (.env.staging, or .env.ENVNAME in general), and our custom command <em>make run-debug env=dev</em> (env=ENVNAME in general), reads this file getting the correct environment related variables and builds up the final command that is actually passed to the terminal to run Flutter with the correct flavor (mapped to android flavors and ios schemes). As an example, our Makefile looks like:</p><pre>env=dev</pre><pre>run-debug-envless:bash scripts/fvm-run.sh flutter runrun-release-envless:bash scripts/fvm-run.sh flutter run --releaserun-debug: .env.$(env)  <br>bash scripts/fvm-run.sh flutter run --flavor $(env) -t lib/main.dart $(shell awk &#39;{print &quot;--dart-define=&quot; $$0}&#39; .env.$(env))run-release: .env.$(env)  <br>bash scripts/fvm-run.sh flutter run --flavor $(env) -t lib/main.dart --release $(shell awk &#39;{print &quot;--dart-define=&quot; $$0}&#39; .env.$(env))</pre><p>where we use FVM to control Flutter version among all developers’ machines over time, and the <em>…-envless </em>version of commands are used when no environment is yet set.<br>For the sake of concreteness, we are going to set as environment variables, just the name of the environment and a mock base url, showing the power of the approach.<br>So, create the files<strong><em> .env.dev, .env.staging </em></strong>and <strong><em>.env.production, </em></strong>add them to .gitignore, and optionally a <strong>.env.example, </strong>that will be kept in source control. Add the values to each file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/0*de-D-koSzo4TG17Y" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/0*_yA73l-HazMQlguK" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/0*YPHxuXHR2AMuG_Gj" /></figure><p>And to receive the variables, let’s create a Env class:</p><pre>class Env {<br>    static const name = String.fromEnvironment(&#39;NAME&#39;);<br>    static const baseUrl = String.fromEnvironment(&#39;BASE_URL&#39;);<br>}class Envs {<br>    static const DEV = &#39;DEV&#39;;<br>    static const STAGING = &#39;STAGING&#39;;<br>    static const PRODUCTION = &#39;PRODUCTION&#39;;<br>}</pre><p>And to your MaterialApp, add the builder option:</p><pre>…<br>builder: (context, child) =&gt; Env.name != Envs.PRODUCTION     ? Env.name.isNotEmpty          ? Banner(<br>              message: Env.name.toString(),<br>              textDirection: TextDirection.ltr,<br>              location: BannerLocation.topStart,<br>              child: child,<br>          )          : Banner(<br>              message: &quot;ENVLESS&quot;,<br>              textDirection: TextDirection.ltr,<br>              location: BannerLocation.topStart,<br>              child: child,<br>          )<br>    : child!,</pre><p>And with that, we’ve already accomplished requirements 1, 2, 3 and 5, and now we have in app differentiation too:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*bGx2Skk-hTvIoV5x.png" /></figure><h3>Firebase Configuration</h3><p>To finish our configuration, we are going to configure the Firebase for each environment, using different projects, as recommended by Firebase Documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*JrLtKMUFR4Xz0RAW" /></figure><ol><li>create a Firebase project for each environment i.e.: capyba-example-dev, capyba-example-staging and capyba-example</li><li>hit to add a flutter app to the project, and the guide will ask you to have the flutterfire cli installed, and point out documentation that helps achieving that.</li><li>Let’s start with one of the environments, i.e. dev. Run the command <strong><em>flutterfire configure — project=capyba-example-dev — ios-bundle-id=com.capyba.example.dev — android-app-id=com.capyba.example.dev</em></strong><br>Note that you need to be authenticated in the account where the project is registered in the FirebaseCli, but don’t worry, the cli will prompt you to do so!</li><li>Select the platforms you want to configure your app into, in this tutorial those are Android, and IOs.</li><li>Once you do that, cli will proceed and register one app for each platform on your Firebase project and generate the related configuration files. In this case, the <em>google-services.json </em>on Android, and <em>firebase_app_id_file.json </em>on IOs. The thing is, those files need to be placed in specific places to be read by each platform during build. For android, it is quite simple, you just move the file to the environment folder (the same that contains environment specific resources folder) like this</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/0*hm3-tFV50kZDFWoJ" /></figure><p>for all environments but production’s. For production you can let the file in the default destination as it was created by FlutterfireCli.<br>For IOs, we need to do a more creative solution. As you can notice in the ios project folder structure, there is no such thing as separate folder for each environment/schema, so the configuration file have just one place to be, and it must have the default name, so the FlutterFire plugin can read the configuration file and connect our flutter app with the correct Firebase project once the app is built. To cope with this, we’ve made use of two suitable scripts, one to delete the previously placed config file from the correct final path, and another to copy the current file to the correct final path. Before proceeding, create a folder inside <strong><em>ios/</em></strong> subfolder named <strong><em>config/ </em></strong>and folders inside it, one for each environment your project will have. In this case, move the just created <em>firebase_app_id_file.json </em>to the folder <em>/ios/config/dev/:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/0*300t7jKd3zdjCr_f" /></figure><p>Go to target <strong>Runner-&gt;Build Phases </strong>and hit the plus icon selecting “New Run Script Phase”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*MQb1p89eTq28Wmbe" /></figure><p>Add two run script phases, name them with a suitable name and drag drop them between <strong><em>Run Script </em></strong>and<strong><em> Compile Sources</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Tqn9Pos-js3JDgKQ" /></figure><p>For, the delete script, paste the code bellow</p><pre>PLIST_DESTINATION=${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app<br>rm &quot;${PROJECT_DIR}/firebase_app_id_file.json&quot;<br>echo &quot;firebase_app_id_file.json deleted&quot;</pre><p>and for the copy script, paste the code (this script was tailored for the case where there are three environments with the names we’ve gave here, remember to adjust the script to your environments names and numbers)</p><pre>PLIST_DESTINATION=${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app<br>echo PLIST_DESTINATION<br>if [ &quot;${CONFIGURATION}&quot; == &quot;Debug-production&quot; ] || [ &quot;${CONFIGURATION}&quot; == &quot;Release-production&quot; ] || [ &quot;${CONFIGURATION}&quot; == &quot;Profile-production&quot; ] || [ &quot;${CONFIGURATION}&quot; == &quot;Release&quot; ]; then<br>cp &quot;${PROJECT_DIR}/config/production/firebase_app_id_file.json&quot; &quot;${PROJECT_DIR}/firebase_app_id_file.json&quot;<br>echo &quot;Production firebase_app_id_file.json copied&quot;<br>elif [ &quot;${CONFIGURATION}&quot; == &quot;Debug-staging&quot; ] || [ &quot;${CONFIGURATION}&quot; == &quot;Release-staging&quot; ] || [ &quot;${CONFIGURATION}&quot; == &quot;Profile-staging&quot; ] || [ &quot;${CONFIGURATION}&quot; == &quot;Debug&quot; ]; then<br>cp &quot;${PROJECT_DIR}/config/staging/firebase_app_id_file.json&quot; &quot;${PROJECT_DIR}/firebase_app_id_file.json&quot;<br>echo &quot;Staging firebase_app_id_file.json copied&quot;<br>elif [ &quot;${CONFIGURATION}&quot; == &quot;Debug-dev&quot; ] || [ &quot;${CONFIGURATION}&quot; == &quot;Release-dev&quot; ] || [ &quot;${CONFIGURATION}&quot; == &quot;Profile-dev&quot; ] || [ &quot;${CONFIGURATION}&quot; == &quot;Debug&quot; ]; then<br>cp &quot;${PROJECT_DIR}/config/dev/firebase_app_id_file.json&quot; &quot;${PROJECT_DIR}/firebase_app_id_file.json&quot;<br>echo &quot;Dev firebase_app_id_file.json copied&quot;<br>fi</pre><p>6. Now, let’s wire things with our .env files. On your dart code, the Flutterfire cli created a <em>firebase_options.dart , </em>and if you go to this file, you are going to see that everything is connected with the correct data of your firebase project for the Dev environment. So, let’s add those values to the <em>.env.dev</em> file, and once we do the same for the other environments, all the data will be placed in the .env files that are going to be read and passed to our dart code during compile time using dart-define. Now our .env file has these fields:</p><pre>NAME=DEV<br>BASE_URL=base_url_dev<br>FIREBASE_ANDROID_API_KEY=<br>FIREBASE_IOS_API_KEY=<br>FIREBASE_MESSAGING_SENDER_ID=<br>FIREBASE_PROJECT_ID=<br>FIREBASE_STORAGE_BUCKET=<br>FIREBASE_ANDROID_APP_ID=<br>FIREBASE_IOS_APP_ID=<br>FIREBASE_IOS_CLIENT_ID=<br>FIREBASE_IOS_BUNDLE_ID=</pre><p>Reproduce the same structure to all your .env.files, and copy the values from the firebase_options.dart to the .env.dev. Now, go to the env.dart file, and create the fields that are going to receive the values from the .env.</p><pre>class Env {<br>    static const name = String.fromEnvironment(&#39;NAME&#39;);<br>    static const url = String.fromEnvironment(&#39;URL&#39;);<br>    static const firebaseAndroidApiKey = String.fromEnvironment(FIREBASE_ANDROID_API_KEY);<br>static const firebaseIosApiKey = String.fromEnvironment(FIREBASE_IOS_API_KEY);<br>    static const firebaseAppIdAndroid =     String.fromEnvironment(&#39;FIREBASE_APP_ID_ANDROID&#39;);<br>    static const firebaseAppIdIos = String.fromEnvironment(&#39;FIREBASE_APP_ID_IOS&#39;);<br>    static const firebaseMessageSenderId =     String.fromEnvironment(&#39;FIREBASE_MESSAGE_SENDER_ID&#39;);<br>    static const firebaseProjectId =     String.fromEnvironment(&#39;FIREBASE_PROJECT_ID&#39;);<br>    static const firebaseStorageBucket =     String.fromEnvironment(&#39;FIREBASE_STORAGE_BUCKET&#39;);<br>    static const firebaseIosClientId =     String.fromEnvironment(&#39;FIREBASE_IOS_CLIENT_ID&#39;);<br>    static const firebaseIosBundleId =     String.fromEnvironment(&#39;FIREBASE_IOS_BUNDLE_ID&#39;);<br>}</pre><p>7. We’re almost there! Repeat the steps 3 to 6 for the rest of the environments, skipping the creation of run script steps, and remember to place the config files in the right place after each run!</p><p>8. As a last step, let’s initialize the FirebaseApp in our main function on dart code, and wire the Env class with the firebase_options file:</p><pre>…<br>static const FirebaseOptions android = FirebaseOptions(<br>   apiKey: Env.firebaseAndroidApiKey,<br>   appId: Env.firebaseAndroidAppId,<br>   messagingSenderId: Env.firebaseMessagingSenderId,<br>   projectId: Env.firebaseProjectId,<br>   storageBucket: Env.firebaseStorageBucket,<br> );static const FirebaseOptions ios = FirebaseOptions(<br>   apiKey: Env.firebaseIosApiKey,<br>   appId: Env.firebaseIosAppId,<br>   messagingSenderId: Env.firebaseMessagingSenderId,<br>   projectId: Env.firebaseProjectId,<br>   storageBucket: Env.firebaseStorageBucket,<br>   iosClientId: Env.firebaseIosClientId,<br>   iosBundleId: Env.firebaseIosBundleId,<br> );</pre><p>and finally initialize the firebase app:</p><pre>void main() async {<br>   WidgetsFlutterBinding.ensureInitialized();await Firebase.initializeApp(<br>   options: DefaultFirebaseOptions.currentPlatform,<br> );…<br>}</pre><h3>Conclusion</h3><p>It was a long run, but after these steps we should have a fully configured project with the desired level of environment differentiation, namely, different apps for each environment showing different app launcher icons, different display names, with in app differentiation and connecting to specific services for each environment. As it stands now, the second semester of 2022, a lot of manual steps are still needed to get something like this working, but we at Capyba understand that it is a low price to pay in comparison with the safety and flexibility in producing different workflows that it brings!</p><p>This is our first attempt to document all this process, and suggestions and improvements are by all means welcome! A special thanks to my tech leader <a href="https://medium.com/u/8e1e73dcd6e0?source=post_page-----dc2575aa93ab--------------------------------">Ibiã Marques</a> for encouraging me to document this, as I believe this builds a lot of value specially for the internal processes at our company, but still might present a valuable source of research for the community as well.</p><p>Another special thanks to <a href="https://medium.com/u/a20c81fc1ff0?source=post_page-----dc2575aa93ab--------------------------------">George Veríssimo</a>, our marketing and general purpose wizard, for always doing his magic in helping format and present content in the best possible way!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb7d085b3b74" width="1" height="1" alt=""><hr><p><a href="https://medium.com/capyba/setting-flutter-environments-the-capybas-way-cb7d085b3b74">Setting Flutter environments. The Capyba’s way</a> was originally published in <a href="https://medium.com/capyba">Capyba</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Viable Architecture choice for real world projects in Flutter]]></title>
            <link>https://medium.com/capyba/a-viable-architecture-choice-for-real-world-projects-in-flutter-579c8f715a1f?source=rss-2d42e00bd33e------2</link>
            <guid isPermaLink="false">https://medium.com/p/579c8f715a1f</guid>
            <category><![CDATA[product-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Kainã Terto Pereira]]></dc:creator>
            <pubDate>Mon, 06 Sep 2021 14:36:01 GMT</pubDate>
            <atom:updated>2021-09-06T14:36:01.247Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*oWJRDbBetuJZ2-dj.png" /></figure><p>As a completely agnostic framework, Flutter is great when it comes to let one free to choose whatever design pattern and architecture it desires. You are free to do all the spaghetti code you want, you can even do all you project in just one file if you wish (although I strongly advise you not to do that). So, when it comes to building up a new project, questions like, ‘what architectural decisions are we going to make?’, ‘which libraries are we going to use?’, ‘what are we going to implement ourselves?’ are going to pop up at the beginning of any exciting new project. In my experience, MVP can be so overwhelming sometimes, tempting not to waste time answering these initial questions, or even not to think about them or patterns to follow in the project, and that is ok, if you are aiming to build a proof of concept, something to show a client and boost a project negotiation or help solving product related issues. But if you need to project which aims to be enduring and maintained by your team or other company, I really believe that an architecture thought to fit to real-life situations, will really help you to build a more reliable, testable and maintainable piece of software.</p><p>Sometimes we take an architecture as a role model and follow it blindly just because someone promised that you were going to avoid a bunch of problems that may never occur during your project’s lifecycle. Here we dared to follow another approach, we’ve started with a robust, well tested and well used architecture, named the<strong><em> </em></strong><a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html"><strong><em>Clean Architecture</em></strong></a> proposed by<strong> Uncle Bob</strong>, and we decided to just shape it and fit it to our real projects technical demands. And we came up with our version of implementation, that may or may not resemble the original ideia, but for us, the important thing was to try to use just as much complexity and abstraction as our projects needed. A disclaimer is important here, far from trying to make a self-contained explanation or to make a pitch of a new revolutionary architecture, the aim here is to document our process, and motivations that moved us towards the decisions we’ve made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*3byjDf9GuEeqaQwg.png" /><figcaption>The clean Architecture from Uncle Bob (Fig. 1)</figcaption></figure><h3>Starting with a good initial implementation</h3><p>We thoroughly followed the path of <a href="https://resocoder.com/blog/"><strong><em>Reso Coder</em></strong></a> and saw the implementation he proposed to the clean architecture and decided it was a good place to start with. This is his schema for his clean architecture’s implementation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/0*zZzajnC5VvfKiZi0.png" /><figcaption>Reso Coder clean architecture implementation proposal (Fig. 2)</figcaption></figure><p>From here we’ve started coding and experimenting to try to get a feel of things by ourselves. As described below.</p><h3>Overview</h3><p>We’ve started with three layers <em>Domain</em>, <em>Data</em> and <em>Presentation </em>like in the original proposal. The <em>Domain</em> layer is the most stable one, and represents components of the system that define the business logic of the application and is as independent as it can be of other layers components. Initially this layer was thought to have <em>Usecase</em>s, <em>Entitie</em>s, and <em>Repository Interface</em>s. But then, after some coding and experimentation, I’ve seen that the repository interface wasn’t really necessary, it looked like we were just trying to keep the purity of the concept of domain not having dependencies from other layers. We’ve decided to not use interfaces, create repositories in the Data layer and just use them!</p><p>The <em>Data</em> layer is the application outmost end, is the place where it communicates with device’s APIs, remote APIs, local databases and so on. Initially it was thought to have <em>Repository implementations</em>, <em>Models</em> and <em>Datasources</em>. As said before, we’ve replaced the implementation of a contract (abstract class interface in the Dart’s context) defined in the Domain layer by an independent implementation of repositories, and it seems to satisfy our needs for now. We then realized that datasources shared the same issue of Repositories Interfaces, it looked to us as they were implemented just for the sake of purity of concept, so we abandoned their use.</p><p>We then have the <em>Presentation</em> layer that is responsible for building the views to interact with the user and receive user’s interactions incomes. This is the most framework dependent layer, it has a multiplicity of implementation options to follow. We’ve started with <em>Views</em> communicating directly with <em>Usecases</em>, then we went for <em>Views</em> that didn’t communicate with <em>Usecases</em> directly, and instead we had <em>Controllers</em> that communicate with <em>Usecases</em>. But it felt that we were adding unnecessary complexity and finally we’ve decided to follow a pattern with <em>SmartViews</em>, and <em>DummyViews</em>, both listening to state changes from the <em>Usecase</em> and emitting events (Kind of a spoiler here! But hold on!).</p><p>As the navigation, showing modals, toast, snackbars and so on, are natively dependent on the context in Flutter, we’ve decided to split the feature/module flow into these two parts: SmartViews are responsible for the navigation, and it can show feature related notifications, but the actual job of drawing the view was decided to be of DummyViews responsibility, and they are also responsible for showing view related notifications (i.e. related with requests that are triggered at the DummyView). They received these names because a SmartView actually knows the entire flow of the feature, it coordinates the navigation following orders from the usecase, and a DummyView doesn’t know anything about the actual flow.</p><p>We felt like a change in the point of view when it comes to where is the fundamental source of truth of the entire system, and we understood that the database and the backend of the system hold that title, and then the concept of Entity would be more fit to live in the Data Layer as it communicates with backend, and conversely the concept of Model would be more fit to be in the Domain layer. (Another disclaimer, this point is just about semantics, and we believed that this made more sense to us).</p><p>At the beginning, there was 8 to 9 architectural elements, and we’ve decided to keep 6 of them, by fusing different elements and their responsibilities or just by not using some elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IyBx3WDOfx2LXyLO.png" /><figcaption>Initial schema of our proposition (Fig. 3)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jwX5gcGkhFDFt9nM.png" /><figcaption>What we came up with (Fig. 4)</figcaption></figure><h3>Real Implementation</h3><p>To materialize the architectural decisions and to make it more useful to our team, we’ve started to choose flutter packages to suit our needs, following the philosophy of using as fewer third-party packages as possible.</p><p>- To implement <em>Usecases</em> as the Business Logic Components of the application, we felt that the natural decision was the <a href="https://pub.dev/packages/flutter_bloc"><strong><em>Bloc package</em></strong></a>, as it is a mature, robust, and well-known solution for state management in <em>Flutter</em> context, and it is easy to test as well.</p><p>- To represent <em>Bloc</em> states and events, <em>Models</em> and <em>Entities</em>, we’ve decided to use <a href="https://pub.dev/packages/freezed"><strong><em>Freezed package</em></strong></a>, as it is an elegant and easy solution to implement sealed classes, union types and data classes as it is not available by default in <em>Dart</em> (yet!). It’s based in code generation and it has ready-to-use integration with <a href="https://pub.dev/packages/json_serializable"><strong><em>Json_serializable package</em></strong></a> that we’ve decided to use to deal with serialization.</p><p>- To deal with dependency injection we’ve decided to use a simple service locator: <a href="https://pub.dev/packages/get_it"><strong><em>GetIt</em></strong></a> and define a simple set of rules-of-thumb to keep consistency over project’s development and maintenance lifecycles. Rules-of-Thumb:</p><blockquote><em>— If a class depends on another, it must be passed at instantiation by constructor and the instance control should be made by the service locator.</em></blockquote><blockquote><em>— Dependency injection setup for a module/feature should be split in each feature (each feature/module will contain its own file explicitly defining its dependency injection setup).</em></blockquote><blockquote><em>— The service locator should never be referenced in a place other than a constructor call.</em></blockquote><p>- To deal with internationalization we’ve decided to use pure Object Oriented Programming, and keep all Strings of the application as static constants of an implementation of an abstract class to be defined.</p><p>- To deal with navigation we’ve decided to use the <em>Flutters</em> native <em>Navigator</em>, as it poses as a complete solution, and with the arrival of <a href="https://docs.google.com/document/d/1Q0jx0l4-xymph9O6zLaOY4d_f7YFpNWX_eGbzYxr9wY/edit#"><strong>Navigator 2.0 api</strong></a>, we think that it is an elegant declarative solution to deal with navigation.</p><p>- To deal with http requests we’ve decided to use <a href="https://pub.dev/packages/dio"><strong>Dio package</strong></a> as it is a better option than the native <em>Flutter</em> solution presenting good features like Interceptors, base options like headers, base url etc., and is a well known and popular solution. Then we made a wrapper over the client to model errors and responses into our system context.</p><p>- To persist sensitive local data we’ve decided to use the package <a href="https://pub.dev/packages/flutter_secure_storage"><strong><em>flutter_secure_storage</em></strong></a> because it is a popular and performatic solution when there isn’t the need of storing complex data.</p><p>We’ve defined helper classes/types to deal with the Result of actions, the <em>Result </em>type (generic Freezed union type that has two types: a <em>Success</em> and a <em>Failure</em>), the<em> RequestStatus </em>type (generic Freezed union type that has four types: <em>Idle</em>, <em>Loading</em>, <em>Succeeded</em>, <em>Failed</em>) to help dealing with the visual response of requests, the AppError (abstract class that is implemented in each relevant particular error type), and to help with forms, the <em>Maybe</em> type (generic Freezed union type that has two types: <em>Nothing</em> and <em>Just</em>) used in the definition of <em>FormField</em> type (generic Freezed dataclass containing the name of the field and the Maybe instance representing the actual possible inputted value to the formfield).</p><h3>Conclusion</h3><p>As we understand, software development is an always evolving craft, and software Architecture seems to evolve with it. We certainly did evolve during the past 2 and a half years of work with this amazing framework that Flutter is, and our understanding and way of doing things with it did evolve too, this article is a consequence of that. The main goal of this article was to document our current architectural implementation with the hope that this might inspire and help others to develop design patterns that would best fit their needs. Currently this implementation seems to satisfy our needs very well, so don’t be shy, try it too!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=579c8f715a1f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/capyba/a-viable-architecture-choice-for-real-world-projects-in-flutter-579c8f715a1f">A Viable Architecture choice for real world projects in Flutter</a> was originally published in <a href="https://medium.com/capyba">Capyba</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>