<?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 Ruslan Tsitser on Medium]]></title>
        <description><![CDATA[Stories by Ruslan Tsitser on Medium]]></description>
        <link>https://medium.com/@RuslanTsitser?source=rss-6114125bf8b4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Xrc0mB75t7x42u4XxeyFDQ.png</url>
            <title>Stories by Ruslan Tsitser on Medium</title>
            <link>https://medium.com/@RuslanTsitser?source=rss-6114125bf8b4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:22:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@RuslanTsitser/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[What is actually BuildContext in flutter]]></title>
            <link>https://medium.com/@RuslanTsitser/what-is-actually-buildcontext-in-flutter-0174a8859192?source=rss-6114125bf8b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/0174a8859192</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ruslan Tsitser]]></dc:creator>
            <pubDate>Tue, 21 May 2024 22:25:16 GMT</pubDate>
            <atom:updated>2024-05-22T06:41:27.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrSvABqY5vnXDkfiiJF-nQ.png" /></figure><p>Today, I will delve into one of the most important topics for a Flutter developer: What is BuildContext and how is it used?</p><p>Let’s start by recalling what a Widget, Element, and RenderObject are.</p><p>A <strong>Widget</strong> is a configuration defined by the developer when writing their StatefulWidget or StatelessWidget. The developer declaratively describes the visual interface by wrapping one widget within another. As a result, we get something like this:</p><pre>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Flutter Demo&#39;,<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>        useMaterial3: true,<br>      ),<br>      home: const StatefulWidgetExample(),<br>    );<br>  }<br>}<br><br><br>class StatefulWidgetExample extends StatefulWidget {<br>  const StatefulWidgetExample({super.key});<br><br>  @override<br>  State&lt;StatefulWidgetExample&gt; createState() =&gt; _StatefulWidgetExampleState();<br>}<br><br>class _StatefulWidgetExampleState extends State&lt;StatefulWidgetExample&gt; {<br>  int _count = 0;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;StatefulWidget Example&#39;),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            Text(<br>              &#39;Count: $_count&#39;,<br>              style: const TextStyle(fontSize: 24),<br>            ),<br>            const SizedBox(height: 16),<br>            ElevatedButton(<br>              onPressed: () {<br>                setState(() {<br>                  _count = 0;<br>                });<br>              },<br>              child: const Text(&#39;Increment Count&#39;),<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>A <strong>RenderObject</strong> is what can be directly rendered on the screen. It can be a line, text, or a red square with specific calculated sizes and coordinates. The developer does not directly interact with the RenderObject, delegating this task to the framework. The framework uses information obtained from the Elements tree.</p><p>An <strong>Element</strong> is an object created at runtime according to the configuration specified by the widgets. It acts as an intermediary between widgets and RenderObjects. At any given time, there is a precisely defined set of elements. <br>When the application’s state changes, such as navigating to a new screen, toggling switches, opening a dialog box, etc., the set of elements also changes strictly within the bounds of the widget configuration described by the developer.</p><p>Simply put, in the Widget Inspector, we see a highly simplified tree of elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*jukLiudouYGqrzQ3UuKXHg.png" /><figcaption>Widget Inspector</figcaption></figure><p>Looking into the documentation, we can see that Element implements the BuildContext interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VHRxIRPc2psUDV2rtEnHIg.png" /><figcaption>Documentation</figcaption></figure><p>This is an example of the ISP (Interface Segregation Principle) from SOLID. Therefore, an element does not necessarily have to contain all methods and fields itself, but rather provide only what is needed in context. Here, we smoothly transition to another SOLID principle — the LSP (Liskov Substitution Principle). Wherever a BuildContext object is required, we can safely use an instance of Element.</p><p>For instance, when using a StatefulWidget, a corresponding StatefulElement is created, and for StatelessWidget — a StatelessElement, which are ultimately all Elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YkPJlKmdMTOUiwfNsQMPOA.png" /><figcaption>ComponentElement</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*A-cQ4YIccvbDgn8kAQB7xg.png" /><figcaption>StatelessElement</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*xKTFc4fu2uLA1VjzFed-Tw.png" /><figcaption>StatefulElement</figcaption></figure><p>Different implementations of Element provide different capabilities for influencing the properties of the Element. The difference between StatefulWidget and StatelessWidget lies only in the extent of influence on the Element that the developer can implement. A pure StatefulWidget, meaning without storing variables in the state, is practically no heavier than a StatelessWidget.</p><p>In build methods, the instance of the Element is used as <strong><em>this</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U2HZFIX2CyaYMgq6B5Agmw.png" /><figcaption>StatelessElement</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zCD7u3Jg-BZLHE432vBbQQ.png" /><figcaption>StatefulElement</figcaption></figure><p>If, for example, you display the result of this code:</p><pre>  Widget build(BuildContext context) {<br>    print(&#39;Hi, this is ${context.runtimeType}&#39;);<br>    ...<br>  }</pre><p>You will get something like “Hi, this is StatefulElement”</p><h3>Conclusion</h3><p>BuildContext is an Element. The advantage of this approach is that the developers cannot directly interact with the Element or invoke its methods. Instead, they can only interact with it through a limited set of methods provided by the BuildContext interface. This should be enough to determine the location in the tree, obtain dependencies, and more..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0174a8859192" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The simplest CI/CD for flutter app with Codemagic. Part 2]]></title>
            <link>https://medium.com/@RuslanTsitser/the-simplest-ci-cd-for-flutter-app-with-codemagic-part-2-8e621eb9bb39?source=rss-6114125bf8b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e621eb9bb39</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ruslan Tsitser]]></dc:creator>
            <pubDate>Sun, 25 Feb 2024 18:31:01 GMT</pubDate>
            <atom:updated>2024-02-26T16:51:17.494Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous article, I told you how to organize the simplest CI/CD for flutter application via Codemagic in case of Android.</p><p><a href="https://medium.com/@RuslanTsitser/the-simplest-ci-cd-for-flutter-app-with-codemagic-part-1-91ec634560d2">The simplest CI/CD for flutter app with Codemagic. Part 1</a></p><p>Today, I’ll tell you how to do a similar thing for iOS. I’ll also give you some small tricks that you can sometimes use, but with great care.</p><p><em>Non-members can read for free </em><a href="https://medium.com/@RuslanTsitser/the-simplest-ci-cd-for-flutter-app-with-codemagic-part-2-8e621eb9bb39?sk=927cdd2c84eef83c13e09c5da0c40437"><em>here</em></a><em>.</em></p><h3>Codemagic setup for iOS. Signing release builds</h3><p>This task looks a thousand times more complicated then similar for Android.</p><p>In order to sign a build that can be sent to the AppStoreConnect, you need:</p><ol><li>A certificate with the extension .p12 and a password to it. <br><strong>Important</strong> — the certificate should be for Apple Distribution or iOS Distribution</li><li>A profile with the extension .mobileprovision for App Store Connect Distribution</li></ol><h4>Certificate .p12</h4><p><strong>Developer’s actions</strong></p><p>First, he has to make a signingRequest on his computer.</p><ul><li>To do this, open Keychain Access</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*VMfF1jOki2_D3dHS.png" /><figcaption>MacOS</figcaption></figure><ul><li>Select “<strong>Request a Certificate From a Certificate Authority…</strong>” and then save file to disk as showed in screenshots</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tKfe3SvoqqUr9PS0.png" /><figcaption>MacOS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I0j_IEsnruBW8UiD.png" /><figcaption>MacOS</figcaption></figure><ul><li>The request file looks like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/0*J7vOYOJf_79yE302.png" /><figcaption>MacOS</figcaption></figure><p><strong>Warning! The following steps can only be done by an App Store Connect account holder if the account is enrolled in the Apple Developer Program as an Individual.</strong></p><ul><li>Open <a href="https://developer.apple.com/account/resources/certificates/list"><strong>Certificates, Identifiers &amp; Profiles</strong></a>, <strong>Certificates </strong>section<strong> </strong>и press the add button</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cJxHzy_JgR2lEA3r.png" /><figcaption>Developer Apple</figcaption></figure><ul><li>Select either <strong>Apple Distribution</strong> or <strong>iOS Distribution </strong>(iOS apps only)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GipW2sdu0aj2_Xdk.png" /><figcaption>Developer Apple</figcaption></figure><ul><li>Upload the created before request file</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qqayTzu_4nWZHVyy.png" /><figcaption>Developer apple</figcaption></figure><ul><li>Download and send the file to the developer from whom the request file received</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j26gk8UxYyjexJkt.png" /><figcaption>Developer Apple</figcaption></figure><ul><li>The result file looks like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/0*aFB4BwK8-QS6aBSf.png" /><figcaption>MacOS</figcaption></figure><p><strong>Developer’s actions. </strong>He has to open <strong>ios_distribution.cer</strong> on his MacOS computer. The he’ll see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PiPNXHa_Y_Lbohn2.png" /><figcaption>MacOS</figcaption></figure><ul><li>Do the export</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EinEZBO5EOfMNH1m.png" /><figcaption>MacOS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ae4Dw898FsHK1wES.png" /><figcaption>MacOS</figcaption></figure><ul><li>I recommend to create a password</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/0*HB1TNqkbWwXZq8bp.png" /><figcaption>MacOS</figcaption></figure><ul><li>The file:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/0*R1itsZDPTqJfrVZJ.png" /><figcaption>MacOS</figcaption></figure><p>Save this for the future.</p><h4>Profile .mobileprovision</h4><p><strong>App Store Connect holder’s actions!</strong></p><ul><li>Open<strong> </strong><a href="https://developer.apple.com/account/resources/profiles/list"><strong>Certificates, Identifiers &amp; Profiles</strong></a>, <strong>Profiles </strong>section<strong> </strong>and press the add button:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*th1J21wJ9C2hFhIH.png" /><figcaption>Developer Apple</figcaption></figure><ul><li>Select <strong>App Store Connect</strong> in the <strong>Distribution </strong>section:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aI3VQjTsoa9WUoZZ.png" /><figcaption>Developer Apple</figcaption></figure><ul><li>Select the app ID what the profile will be used for:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RjiJbPnhIFDT7wNq.png" /><figcaption>Developer Apple</figcaption></figure><ul><li>Select the created in the previous steps certificate</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*poWoymUlAcT0MmEG.png" /><figcaption>Developer Apple</figcaption></figure><ul><li>Write a name, download and sent to the developer</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4gPXXIvkyW7pPAw_.png" /><figcaption>Developer Apple</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Prw6vOAEKJimpzgz.png" /><figcaption>Developer Apple</figcaption></figure><ul><li>The file:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/0*gI7j1o-UMlR6ZzbN.png" /><figcaption>MacOS</figcaption></figure><p><em>Remember, when adding some new feature that was not previously in the app, such as in-app purchases, you will need to create a new profile!</em></p><h4>Codemagic</h4><p>You have certificate .p12 and profile .mobileprovision. Now you can add them to the codemagic. That’s easy:</p><ul><li>Expand <strong>iOS code signing </strong>section</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EuWsSjLvGoFbY3jZ.png" /><figcaption>Codemagic.io</figcaption></figure><ul><li>Select the <strong>Manual</strong> method, upload files and enter certificate’s password</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZcwnhlCEvAiK9h8U.png" /><figcaption>Codemagic.io</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q-xaSq8h0d1qtagw.png" /><figcaption>Codemagic.io</figcaption></figure><p>After submit you’ll see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bZf7_O4gilkY8IXv.png" /><figcaption>Codemagic.io</figcaption></figure><p>After running the build on iOS and completing it successfully, you should get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*whwl58JReuGQQHmA.png" /><figcaption>Codemagic.io</figcaption></figure><p>You can also download artifacts and manually send them to their destination.</p><h3>Codemagic setup for iOS. Automatic sending to App Store Connect (TestFlight)</h3><p>Unlike Android with the Google Cloud Console setup, here it’s simpler than it might seem after the previous steps.</p><p><strong>App Store Connect Account holder’s actions</strong></p><ul><li>First, Open <strong>Users and Access</strong>, <strong>Integrations</strong> section (<a href="https://appstoreconnect.apple.com/access/integrations/api">link</a>) and press the add button to create an new key</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GAJ1pi3D9sLhUYGd.png" /><figcaption>App Store Connect</figcaption></figure><ul><li>An access level should be at least <strong>App Manager</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*36x6IaBzCrnjEqtN.png" /><figcaption>App Store Connect</figcaption></figure><ul><li>The key can be downloaded <strong>only once</strong>. Also it’s important to save an <strong>Issuer ID</strong> and <strong>KEY ID </strong>from this page and use them later</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OHtjN45hnCzqZGWI.png" /><figcaption>App Store Connect</figcaption></figure><p>The file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/0*GiU8-VKPxTp8spXv.png" /><figcaption>MacOS</figcaption></figure><p>This file has to be sent to the developer.</p><p><strong>The following steps can be done by the developer.</strong></p><ul><li>Expand the <strong>App Store Connect</strong> section on Codemagic and “Go to settings”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ITF1P6ropsMn2UlD.png" /><figcaption>Codemagic.io</figcaption></figure><ul><li>Connect to <strong>Developer Portal</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JLr1cRh81xPgQucg.png" /><figcaption>Codemagic.io</figcaption></figure><ul><li>Fill in the required fields, upload the file and come up with a key name</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x10dqjrwegCqGlW7.png" /><figcaption>Codemagic.io</figcaption></figure><ul><li>Select the created API key in the <strong>App Store Connect</strong> section</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZdzNYyNnxVRVfPJI.png" /><figcaption>Codemagic.io</figcaption></figure><p>If everything is configured correctly, you will get this result after running the build on iOS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HVLlGTGvdHA_fJC4.png" /><figcaption>Codemagic.io</figcaption></figure><p>And in TestFlight:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_ka3Mey0R5ciBQxD.png" /><figcaption>App Store Connect</figcaption></figure><h3>About Codemagic limitations</h3><p>Like any service, Codemagic has its limitations and restrictions, which are solved by activating paid subscriptions. You should also familiarize yourself with this before using the service:</p><p><a href="https://codemagic.io/pricing/">Pricing | Codemagic</a></p><p>In other words, the service is free. But if you want additional features like adding other members of the development team, you will have to pay. This is something everyone decides for themselves.</p><h3>Conclusion</h3><p>Today we have covered in detail how to organize CI/CD to build and publish a flutter app to App Store Connect using Codemagic.</p><p>Briefly, what is required for a developer to set up for iOS:</p><ul><li>A <strong>.p12</strong> certificate, its password, and a <strong>.mobileprovision</strong> profile to sign the build</li><li>App Store Connect API Key <strong>.p8</strong>, <strong>Issuer ID </strong>and <strong>Key ID</strong> — to publish to App Store Connect (TestFlight)</li></ul><p>What the App Store Connect account holder needs to do:</p><ul><li>Prepare all necessary files for the developer</li></ul><p>It is enough to create all the necessary files once and send them to developers when necessary, so that you don’t have to perform all these actions repeatedly. But this should also be done with great care, so that no one extra can get access to accounts or any important resources.</p><p>If you liked the material, follow me to get more.</p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e621eb9bb39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The simplest CI/CD for flutter app with Codemagic. Part 1]]></title>
            <link>https://medium.com/@RuslanTsitser/the-simplest-ci-cd-for-flutter-app-with-codemagic-part-1-91ec634560d2?source=rss-6114125bf8b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/91ec634560d2</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Ruslan Tsitser]]></dc:creator>
            <pubDate>Sun, 25 Feb 2024 13:04:21 GMT</pubDate>
            <atom:updated>2024-02-26T16:52:07.042Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s say you are a developer on some small project. There is only limited access to App Store Connect and Google Play Console. These are such restrictions: like signing builds and publishing to the marketplaces.</p><p>Of course, you can bypass these restrictions if you make the necessary certificates and profiles (in the case of iOS) or using the original jks file and passwords to it (in the case of Android). To do this, you usually need to ask the owner of these accounts.</p><p>This article will be useful to you if you see yourself in at least one of the above cases:</p><ol><li>The process of building for iOS or Android takes too much time and resources of your computer</li><li>There is another developer on the project who is actively engaged in the project and is making some changes day to day, but only you can do the build</li><li>The Project Manager has asked you to send another build to the testers, but you don’t have access to your computer</li></ol><p>This will be a detailed tutorial with many screenshots.</p><p><em>Non-members can read for free </em><a href="https://medium.com/@RuslanTsitser/the-simplest-ci-cd-for-flutter-app-with-codemagic-part-1-91ec634560d2?sk=75c560a2805ddb4f336487da917d8193"><em>here</em></a><em>.</em></p><h3>Minimum requirements for iOS and Android</h3><p><strong>Signing for release builds</strong>:</p><ul><li><strong>iOS</strong>: <br>certificate.p12 (Distribution or iOS Distribution) and its password; <br>profile.mobileprovision (App Store Connect Distribution)</li><li><strong>Android</strong>: <br>keystore.jks and passwords to it</li></ul><p><strong>Access to Stores API</strong> — for generally organizing the process of sending to Stores via third-party services like Codemagic, GitHub Actions, Fastlane and others:</p><ul><li><strong>App Store Connect API</strong>: <br>IssuerID<br>App Store Connect API Key with .p8 extension</li><li><strong>Google Play Android Developer API</strong>: <br>json file of the Service Account from the project in Google Cloud Console</li></ul><h3>Codemagic Registration</h3><p>Initial prerequisites:</p><ol><li>Have an account on GitHub, GitLab, or BitBucket</li><li>Have access to the project repository</li></ol><p>First, you need to create an account with Codemagic if you don’t already have one:</p><p><a href="https://codemagic.io/login">CI/CD for Android, iOS, Flutter and React Native projects</a></p><p>It’s easy. You just have to click on the most bright buttons:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9U3fW2IrPnQ6hamd.png" /><figcaption>Codemagic.io</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gj2OZy6WlmfsB0XI.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gDPxUZ4NSBB56owB.png" /><figcaption>Codemagic.io</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fV_8ZEEhuodyb-EN.png" /><figcaption>Codemagic.io</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e7m42kn_uwp6yxvb.png" /><figcaption>Codemagic.io</figcaption></figure><p>In the end you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WO1HsCkZLh0xrML0.png" /><figcaption>Codemagic.io</figcaption></figure><p>Let’s break down how to set up CI/CD</p><h3>Codemagic setup for Android. Signing release builds</h3><p>This, in my opinion, is the easiest.</p><p>It will require:</p><ol><li>A <strong>jks</strong> file to sign the release build</li><li>Passwords and Key Alias</li></ol><h4>Project setup</h4><p>On my projects the android folder usually looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*MUc1wViIfL3FKWgx.png" /><figcaption>VSCode</figcaption></figure><ul><li><strong>android/app/build.gradle</strong> — the following condition should be added here:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qol5MOr1fkozQH8h.png" /><figcaption>VSCode</figcaption></figure><pre>if (System.getenv()[&quot;CI&quot;]) { // CI=true is exported by Codemagic<br>    storeFile file(System.getenv()[&quot;CM_KEYSTORE_PATH&quot;])<br>    storePassword System.getenv()[&quot;CM_KEYSTORE_PASSWORD&quot;]<br>    keyAlias System.getenv()[&quot;CM_KEY_ALIAS&quot;]<br>    keyPassword System.getenv()[&quot;CM_KEY_PASSWORD&quot;]<br>} else {<br>    keyAlias keystoreProperties[&#39;keyAlias&#39;]<br>    keyPassword keystoreProperties[&#39;keyPassword&#39;]<br>    storeFile keystoreProperties[&#39;storeFile&#39;] ? file(keystoreProperties[&#39;storeFile&#39;]) : null<br>    storePassword keystoreProperties[&#39;storePassword&#39;]<br>}</pre><ul><li><strong>andoid/key.properties</strong> — all secrets are usually stored here, they are required to access the keystore file for the release build. This data will be used in Codemagic later.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RR0eIGCRSnmJSe4i.png" /><figcaption>VSCode</figcaption></figure><p><strong><em>Just in case I remind you that this file should not be stored in public access, especially if the project is public!</em></strong></p><h4>Codemagic setup</h4><ul><li>Expand the <strong>Build</strong> section</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tHjeit2kCAbGwoiq.png" /><figcaption>Codemagic.io</figcaption></figure><ul><li>It should be <strong>Release</strong> mode selected</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4ci98TT3n7ilFmD1.png" /><figcaption>Codemagic.io</figcaption></figure><ul><li>Expand the <strong>Distribution</strong> section</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kmytzLrc0F4nJIX_.png" /><figcaption>Codemagic.io</figcaption></figure><ul><li>Upload the <strong>keystore.jks</strong> file and fill the fields with data from the <strong>key.properties</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1p96OccHG9UJSOvY.png" /><figcaption>Codemagic.io</figcaption></figure><ul><li>After these step you should see something like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ArX5URj8K_6n4V6r.png" /><figcaption>Codemagic.io</figcaption></figure><p>In general, this is enough for building not on your computer. After clicking on Start new build, you will only have to select the branch you want to build from.</p><p>After successful build it will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/0*nbutJff_xbgWooMO.png" /><figcaption>Codemagic.io</figcaption></figure><p>You can manually download artifacts and send them to their destination.</p><h3>Codemagic setup for Android. Automatic publishing to Google Play</h3><p>This step, as I mentioned above, requires the access to the <strong>Google Play Android Developer API</strong></p><p>First, you need to open an existing project in <a href="https://console.cloud.google.com/">Google Cloud Console</a> or create a new one. <em>Or you can, for example, use an existing Firebase project.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZEFX3aWRnYot3OV2.png" /><figcaption>Google Cloud Console</figcaption></figure><ul><li>Enable <strong>Google Play Android Developer API</strong>. Follow the <a href="https://console.cloud.google.com/apis/library/androidpublisher.googleapis.com">link</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yIrMIre-f3UL0j8v.png" /><figcaption>Google Cloud Console</figcaption></figure><ul><li>Create a new Service Account (<a href="https://console.cloud.google.com/iam-admin/serviceaccounts">link</a>), grant the permission of <strong>Service Account User</strong> and save its email for the future. <br><em>In this example, the email is codemagic@tsitser-game.iam.gserviceaccount.com</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mGdRQs7JZZktY4Ho.png" /><figcaption>Google Cloud Console</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gGcQg6GrCw6KToMo.png" /><figcaption>Google Cloud Console</figcaption></figure><ul><li>Create and save a <strong>private key</strong> <strong>JSON</strong> of this Service Account</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hxhiCf8nMOgHPBQY.png" /><figcaption>Google Cloud Console</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VvYAm3CXRAeLifb0.png" /><figcaption>Google Cloud Console</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lQUq9HC7GF4o8oEN.png" /><figcaption>Google Cloud Console</figcaption></figure><ul><li>Upload the <strong>Private Key JSON </strong>to Codemagic</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*myucsj5gMGSpIC6V.png" /><figcaption>Codemagic.io</figcaption></figure><p><strong>Warning! The following steps require Admin permissions in Google Play Console</strong></p><ul><li>Go to the <strong>App integrity</strong> section of Google Play Console and link to the Cloud Project</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sEVVNDUq1iJXcHLC.png" /><figcaption>Google Play Console</figcaption></figure><ul><li>If you have the permissions you see something like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X8RftOqHe0PSTHLD.png" /><figcaption>Google Play Console</figcaption></figure><ul><li>After that you have to got to the <strong>Users and Permissions </strong>section, add previously saved email of the Service Account from the Google Cloud Console<br><em>This is codemagic@tsitser-game.iam.gserviceaccount.com in my example.<br>You can save the default permissions</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QCqe_OrDXkjcM02c.png" /><figcaption>Google Play Console</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OWQsCjEd9nxgXarf.png" /><figcaption>Google Play Console</figcaption></figure><p>If everything is configured correctly, then after running the build you will see the similar result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ljn5gjFFtgunOpBU.png" /><figcaption>Codemagic.io</figcaption></figure><p>And in the Google Play Console you will see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s4TcpK1w09zEqG-_.png" /><figcaption>Google Play Console</figcaption></figure><h3>Conclusions</h3><p>Today we looked at how to easily organize CI/CD to build and publish a flutter app to Google Play using Codemagic.</p><p>What is required for a developer:</p><ol><li>Access to the project repository</li><li>A keystore file for signing of release builds and passwords to it</li><li>Admin permissions in Google Play Console</li></ol><p>What is required to do for the Google Play Account Holder:</p><ol><li>Give admin rights to the developer</li></ol><p>The next article will be about setting up CI/CD for iOS and publishing to App Store Connect (TestFlight), as well as briefly talk about the limitations of this service and other important points.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91ec634560d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gyroscopic Parallax Effect in Flutter]]></title>
            <link>https://medium.com/@RuslanTsitser/gyroscopic-parallax-effect-in-flutter-43ceb53b1449?source=rss-6114125bf8b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/43ceb53b1449</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ruslan Tsitser]]></dc:creator>
            <pubDate>Sun, 18 Feb 2024 13:38:32 GMT</pubDate>
            <atom:updated>2024-05-21T20:37:41.647Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to implement gyroscopic Parallax in Flutter</h3><p>I recently covered how to create a parallax effect when scrolling using the CustomPaint widget</p><p><a href="https://medium.com/@RuslanTsitser/create-a-parallax-effect-in-flutter-with-custompaint-9b169a7bc386">Create a parallax effect in Flutter with CustomPaint</a></p><p>Today, I’m going to tell you how you can bring a picture to life with a simple tilt of your phone</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*gE0F7hp7XD8U0zH3.gif" /><figcaption>Result</figcaption></figure><h4>Introduction</h4><p>Let’s remember what has already been implemented in the previous article:</p><ol><li>A screen with a list of items. Each item is a picture with a caption</li><li>A background that also shifts when scrolling, but a bit slower than the items in the list</li></ol><pre>import &#39;dart:math&#39; show Random;<br>import &#39;dart:ui&#39; as ui;<br><br>import &#39;package:flutter/material.dart&#39;;<br><br>class ParallaxScreen extends StatefulWidget {<br>  const ParallaxScreen({super.key});<br><br>  @override<br>  State&lt;ParallaxScreen&gt; createState() =&gt; _ParallaxScreenState();<br>}<br><br>class _ParallaxScreenState extends State&lt;ParallaxScreen&gt; {<br>  // get an array of random ids<br>  late final List&lt;int&gt; ids = List.generate(10, (index) =&gt; Random().nextInt(500));<br><br>  // controller to handle scrolling of items<br>  final ScrollController _scrollController = ScrollController();<br><br>  @override<br>  void dispose() {<br>    _scrollController.dispose();<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: _Background(<br>        scrollController: _scrollController,<br>        child: ListView.builder(<br>          controller: _scrollController,<br>          itemCount: ids.length,<br>          itemBuilder: (context, index) {<br>            final int id = ids[index];<br>            return ItemCard(id: id);<br>          },<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>class ItemCard extends StatelessWidget {<br>  const ItemCard({<br>    super.key,<br>    required this.id,<br>  });<br><br>  final int id;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Container(<br>      margin: const EdgeInsets.symmetric(<br>        horizontal: 20,<br>        vertical: 20,<br>      ),<br>      clipBehavior: Clip.hardEdge,<br>      width: double.maxFinite,<br>      height: 300,<br>      decoration: BoxDecoration(<br>        color: Colors.grey.withOpacity(0.4),<br>        borderRadius: BorderRadius.circular(20),<br>        boxShadow: const [<br>          BoxShadow(<br>            color: Colors.black12,<br>            blurRadius: 10,<br>            spreadRadius: 5,<br>          ),<br>        ],<br>      ),<br>      child: Stack(<br>        children: [<br>          Image.network(<br>            &#39;https://picsum.photos/id/$id/500/300&#39;, // get an image from network by id<br>            width: double.maxFinite,<br>          ),<br>          Positioned(<br>            left: 20,<br>            bottom: 20,<br>            child: Text(<br>              &#39;Image $id&#39;,<br>              style: const TextStyle(<br>                color: Colors.white,<br>                fontSize: 24,<br>                fontWeight: FontWeight.bold,<br>              ),<br>            ),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}<br><br>class _Background extends StatefulWidget {<br>  const _Background({<br>    required this.child,<br>    required this.scrollController,<br>  });<br>  final Widget child;<br>  final ScrollController scrollController;<br><br>  @override<br>  State&lt;_Background&gt; createState() =&gt; _BackgroundState();<br>}<br><br>class _BackgroundState extends State&lt;_Background&gt; {<br>  @override<br>  void initState() {<br>    super.initState();<br>    _loadImage();<br>  }<br><br>  ui.Image? _image;<br>  // logic for downloaiding an image as ui.Image object<br>  Future&lt;void&gt; _loadImage() async {<br>    const imageProvider = NetworkImage(&#39;https://picsum.photos/id/307/600/4000&#39;); // get background image. You can use anyone you want<br>    final ImageStreamListener listener = ImageStreamListener((info, _) {<br>      setState(() {<br>        _image = info.image;<br>      });<br>    });<br>    final ImageStream stream = imageProvider.resolve(const ImageConfiguration());<br>    stream.addListener(listener);<br>  }<br><br>  @override<br>  void dispose() {<br>    _image?.dispose();<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return CustomPaint(<br>      painter: _image != null ? _BackgroundImagePainter(widget.scrollController, _image!) : null,<br>      child: widget.child,<br>    );<br>  }<br>}<br><br>class _BackgroundImagePainter extends CustomPainter {<br>  final ScrollController controller;<br>  final ui.Image image;<br>  const _BackgroundImagePainter(this.controller, this.image) : super(repaint: controller);<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final imageWidth = image.width.toDouble();<br>    final imageHeight = image.height.toDouble();<br>    final aspectRatio = imageWidth / imageHeight;<br><br>    final src = Rect.fromLTWH(<br>      0,<br>      0,<br>      imageWidth,<br>      imageHeight,<br>    );<br>    final deltaY = -controller.offset * 0.6;<br>    final dst = Rect.fromLTWH(<br>      0,<br>      deltaY,<br>      size.width,<br>      size.width / aspectRatio,<br>    );<br>    canvas.drawImageRect(<br>      image,<br>      src,<br>      dst,<br>      Paint()..filterQuality = FilterQuality.high,<br>    );<br>  }<br><br>  @override<br>  bool shouldRepaint(_BackgroundImagePainter oldDelegate) =&gt; controller.offset != oldDelegate.controller.offset;<br>}</pre><p>In order to react to the phone’s tilts, you need to receive data from the device’s sensors. Therefore, this case is relevant only on devices with accelerometer and gyroscope</p><p><strong>Accelerometer</strong> is a sensor that measures acceleration when the device is moving in real time in three projections. The unit of measurement is either m/c², or a value between 0 and 1 (normalized relative to the gravitational acceleration of 9.8 m/s²). If, for example, the phone is lying on a table, the absolute value of the acceleration will be either 9.8 or 1 on the Z-axis</p><p><strong>Gyroscope</strong> is a sensor that indicates how fast the device has been rotated relative to axis X, Y or Z. The unit of measurement is either °/s or rad/s. If the body is at rest, the sensor shows zero values</p><h3>Existing libraries</h3><p>To get data from these sensors, there are several ready-made solutions on pub.dev</p><h4>flutter_sensors</h4><p><a href="https://pub.dev/packages/flutter_sensors">flutter_sensors | Flutter package</a></p><p>This is an example of a library that has existed for more than 2 years without updates, is supported in the current version of flutter and dart and fulfills its tasks quite well. I used this library in my early projects</p><h4>sensors_plus</h4><p><a href="https://pub.dev/packages/sensors_plus">sensors_plus | Flutter package</a></p><p>This is an example of another library that has a simpler API compared to flutter_sensors, and does not require additional permission settings in AndroidManifest.xml for Android or info.plist for iOS. <br>Another difference is that the acceleration calculation uses different units. This is worth considering when migrating from one library to another.</p><p>In this example we will use sensors_plus</p><h3>Quick upgrade</h3><ol><li>Add the sensors_plus library to pubspec.yaml</li></ol><pre>name: parallax_with_sensors_example<br>description: &quot;A new Flutter project.&quot;<br>publish_to: &quot;none&quot;<br>version: 0.1.0<br><br>environment:<br>  sdk: &quot;&gt;=3.2.6 &lt;4.0.0&quot;<br><br>dependencies:<br>  flutter:<br>    sdk: flutter<br>  sensors_plus: any # Add this line<br><br>dev_dependencies:<br>  flutter_lints: ^2.0.0<br>  flutter_test:<br>    sdk: flutter<br><br>flutter:<br>  uses-material-design: true</pre><p>2. Add import to the file where the ParallaxScreen widget is implemented</p><pre>import &#39;dart:async&#39;;<br>import &#39;dart:ui&#39; as ui;<br><br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:sensors_plus/sensors_plus.dart&#39;; // add this line</pre><p>3. Refactor the ParallaxScreen implementation</p><pre>  @override<br>  Widget build(BuildContext context) {<br>    return StreamBuilder&lt;AccelerometerEvent&gt;(<br>        stream: accelerometerEventStream(samplingPeriod: SensorInterval.uiInterval),<br>        builder: (context, snapshot) {<br>          final x = snapshot.data?.x ?? 0;<br>          final y = snapshot.data?.y ?? 0;<br>          return AnimatedContainer(<br>            duration: const Duration(milliseconds: 100),<br>            transform: Matrix4.identity()..translate(x * 10, y * 10),<br>            child: CustomPaint(<br>              painter: _image != null ? _BackgroundImagePainter(widget.scrollController, _image!) : null,<br>              child: widget.child,<br>            ),<br>          );<br>        });<br>  }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*FuVvy7bkpLB9BLzj.gif" /><figcaption>Imlementation with Accelerometer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*EB6JKxH8g3djffZP.gif" /><figcaption>Implementation with Gyroscope</figcaption></figure><h4>What we have with this implementation:</h4><ul><li>We use <strong>StreamBuilder</strong>, because the data from the sensors comes as a stream; <br>If you don’t know much about Streams in Dart, but are familiar, for example, with YouTube, then can image a stream, when some blogger shows something, and watchers can see it in real time. In simple words, the blogger put a picture into a tube (Sink), and users receive this picture from the tube (Stream). <br>With sensors it is approximately the same: in real time data with a certain frequency is collected and transmitted to Sink. If someone connects to the Stream of this tube then he will receive this data</li><li>The data comes in units/decimals, so to increase sensitivity we multiply by 10 (at your discretion).</li><li>The <strong>samplingPeriod</strong> field specifies the frequency with which to collect data from the sensors</li><li>In the code example, the data is taken from the accelerometer. <br>This choice preserves the position of the picture after the tilt is complete. <br>For a gyroscope, the picture will return to the original position after the end of rotation.</li><li>AnimatedContainer — used simply for smooth animation</li></ul><p>A variant of the code about how you can move only the picture on the background:</p><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Stack(<br>      children: [<br>        StreamBuilder&lt;AccelerometerEvent&gt;(<br>            stream: accelerometerEventStream(samplingPeriod: SensorInterval.uiInterval),<br>            builder: (context, snapshot) {<br>              final x = snapshot.data?.x ?? 0;<br>              final y = snapshot.data?.y ?? 0;<br>              return AnimatedContainer(<br>                duration: const Duration(milliseconds: 100),<br>                transform: Matrix4.identity()..translate(x * 10, y * 10),<br>                child: CustomPaint(<br>                  size: Size.infinite,<br>                  painter: _image != null ? _BackgroundImagePainter(widget.scrollController, _image!) : null,<br>                ),<br>              );<br>            }),<br>        widget.child,<br>      ],<br>    );<br>  }</pre><h3>Conclusion</h3><p>Today we looked at a simple option of how you can add responsiveness to your application when interacting with the real world using gyroscope and accelerometer.</p><p>If you liked this article, please hit 👏 to let me know that the topic is interesting and I will write more articles like this one</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43ceb53b1449" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a parallax effect in Flutter with CustomPaint]]></title>
            <link>https://medium.com/@RuslanTsitser/create-a-parallax-effect-in-flutter-with-custompaint-9b169a7bc386?source=rss-6114125bf8b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b169a7bc386</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ruslan Tsitser]]></dc:creator>
            <pubDate>Thu, 15 Feb 2024 14:07:12 GMT</pubDate>
            <atom:updated>2024-05-21T20:36:51.134Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to implement parallax effect in Flutter with CustomPaint</h3><p>In today’s world of mobile development, where attention to detail and uniqueness of the interface play a key role, the parallax effect opens new horizons for user engagement. There are many different ways to implement it, such as through Flow or PageView. In this article, we will reveal how to use CustomPaint to bring an application on Flutter to life by adding the parallax effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*bK6Z18s61bjQKjGn0ySH7A.gif" /></figure><blockquote><strong>The parallax effect</strong>, as an artistic technique in design, creates the illusion of depth and movement. This is achieved by varying the speed of movement of image layers, giving dynamism and depth to visual elements. For example, the background can move slower than the front elements, creating the impression of multidimensionality.</blockquote><h3>Task</h3><p>Let’s assume that a task to build a screen, and a creative designer came up with an idea of a long vertical picture on the background and a certain number of elements in the foreground. The background picture should shift slower relative to the main content, creating a parallax effect.</p><p>For simplicity of implementation let it be identical elements representing semi-transparent cards with random images.</p><h4><strong>Image Card Widget</strong>.</h4><p>Let’s use the service <a href="https://picsum.photos/">https://picsum.photos/</a> to get eye pleasing images:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class ItemCard extends StatelessWidget {<br>  const ItemCard({<br>    super.key,<br>    required this.id,<br>  });<br><br>  final int id;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Container(<br>      margin: const EdgeInsets.symmetric(<br>        horizontal: 20,<br>        vertical: 20,<br>      ),<br>      clipBehavior: Clip.hardEdge,<br>      width: double.maxFinite,<br>      height: 300,<br>      decoration: BoxDecoration(<br>        color: Colors.grey.withOpacity(0.4),<br>        borderRadius: BorderRadius.circular(20),<br>        boxShadow: const [<br>          BoxShadow(<br>            color: Colors.black12,<br>            blurRadius: 10,<br>            spreadRadius: 5,<br>          ),<br>        ],<br>      ),<br>      child: Stack(<br>        children: [<br>          Image.network(<br>            &#39;https://picsum.photos/id/$id/500/300&#39;,<br>            width: double.maxFinite,<br>          ),<br>          Positioned(<br>            left: 20,<br>            bottom: 20,<br>            child: Text(<br>              &#39;Image $id&#39;,<br>              style: const TextStyle(<br>                color: Colors.white,<br>                fontSize: 24,<br>                fontWeight: FontWeight.bold,<br>              ),<br>            ),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><h4><strong>Implementation of a screen</strong> with a scrolling list.</h4><p>Picture id’s are selected randomly:</p><pre>import &#39;dart:math&#39; show Random;<br><br>import &#39;package:flutter/material.dart&#39;;<br><br><br>class ParallaxScreen extends StatefulWidget {<br>  const ParallaxScreen({super.key});<br><br>  @override<br>  State&lt;ParallaxScreen&gt; createState() =&gt; _ParallaxScreenState();<br>}<br><br>class _ParallaxScreenState extends State&lt;ParallaxScreen&gt; {<br>  late final List&lt;int&gt; ids = List.generate(10, (index) =&gt; Random().nextInt(500));<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: ListView.builder(<br>        itemCount: ids.length,<br>        itemBuilder: (context, index) {<br>          final int id = ids[index];<br>          return ItemCard(id: id);<br>        },<br>      ),<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*agoonO4apmWgqwPn25N3oQ.gif" /></figure><h4><strong>Background</strong></h4><p>We will implement the background through CustomPainter, as it is relatively easy to perform various manipulations with ui.Image. To track scrolling in the list we will use ScrollController</p><pre>import &#39;dart:ui&#39; as ui;<br><br>import &#39;package:flutter/material.dart&#39;;<br><br>class _BackgroundImagePainter extends CustomPainter {<br>  final ScrollController controller;<br>  final ui.Image image;<br>  const _BackgroundImagePainter(this.controller, this.image) : super(repaint: controller);<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final imageWidth = image.width.toDouble();<br>    final imageHeight = image.height.toDouble();<br>    final aspectRatio = imageWidth / imageHeight;<br><br>    final src = Rect.fromLTWH(<br>      0,<br>      0,<br>      imageWidth,<br>      imageHeight,<br>    );<br>    final deltaY = -controller.offset * 0.6;<br>    final dst = Rect.fromLTWH(<br>      0,<br>      deltaY,<br>      size.width,<br>      size.width / aspectRatio,<br>    );<br>    canvas.drawImageRect(<br>      image,<br>      src,<br>      dst,<br>      Paint()..filterQuality = FilterQuality.high,<br>    );<br>  }<br><br>  @override<br>  bool shouldRepaint(_BackgroundImagePainter oldDelegate) =&gt; controller.offset != oldDelegate.controller.offset;<br>}</pre><p><strong>Brief Explanation:</strong></p><ul><li>We pass the scrollController to the repaint field of the parent super constructor so that customPainter responds to scrolling</li><li>aspectRatio — the aspect ratio of the picture. It is necessary for the picture not to be stretched or squashed.</li><li>We use the canvas.drawImageRect method, which I described in this article</li></ul><p><a href="https://medium.com/@RuslanTsitser/how-to-implement-image-cropping-in-flutter-without-third-party-libraries-a0e1597ad435">How to implement image cropping in flutter without third-party libraries</a></p><ul><li>src is the part of the image that we want to display, and here we should specify the real size of the image</li><li>dst is a rectangle in which we want to draw the part cut from src</li><li>In this implementation the picture is drawn completely and goes beyond the visible area of the screen in height. <br>*Here you can optimize if you want, so that you don’t have to keep in memory the part that is not displayed on the screen.</li><li>When scrolling, the picture is shifted along the Y axis by the deltaY value equal to -controller.offset * 0.6, where 0.6 is the coefficient by which the parallax effect is achieved.</li></ul><h4>Background Widget</h4><p>The widget itself:</p><pre>import &#39;dart:ui&#39; as ui;<br><br>import &#39;package:flutter/material.dart&#39;;<br><br>class _Background extends StatefulWidget {<br>  const _Background({<br>    required this.child,<br>    required this.scrollController,<br>  });<br>  final Widget child;<br>  final ScrollController scrollController;<br><br>  @override<br>  State&lt;_Background&gt; createState() =&gt; _BackgroundState();<br>}<br><br>class _BackgroundState extends State&lt;_Background&gt; {<br>  @override<br>  void initState() {<br>    super.initState();<br>    _loadImage();<br>  }<br><br>  ui.Image? _image;<br>  Future&lt;void&gt; _loadImage() async {<br>    const imageProvider = NetworkImage(&#39;https://picsum.photos/id/307/600/4000&#39;);<br>    final ImageStreamListener listener = ImageStreamListener((info, _) {<br>      setState(() {<br>        _image = info.image;<br>      });<br>    });<br>    final ImageStream stream = imageProvider.resolve(const ImageConfiguration());<br>    stream.addListener(listener);<br>  }<br><br>  @override<br>  void dispose() {<br>    _image?.dispose();<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return CustomPaint(<br>      painter: _image != null ? _BackgroundImagePainter(widget.scrollController, _image!) : null,<br>      child: widget.child,<br>    );<br>  }<br>}</pre><p><strong>Brief Explanation:</strong></p><ul><li>The _loadImage method uses an ImageProvider implemented via NetworkImage to load an image. If, for example, it is necessary to get an image from another source, there are default image providers as AssetImage or FileImage</li><li>CustomPaint accepts child sizes, so you don’t need to specify size</li></ul><h4>The final code of the implemented screen</h4><pre>import &#39;dart:math&#39; show Random;<br><br>import &#39;package:flutter/material.dart&#39;;<br><br>class ParallaxScreen extends StatefulWidget {<br>  const ParallaxScreen({super.key});<br><br>  @override<br>  State&lt;ParallaxScreen&gt; createState() =&gt; _ParallaxScreenState();<br>}<br><br>class _ParallaxScreenState extends State&lt;ParallaxScreen&gt; {<br>  late final List&lt;int&gt; ids = List.generate(10, (index) =&gt; Random().nextInt(500));<br>  final ScrollController _scrollController = ScrollController();<br><br>  @override<br>  void dispose() {<br>    _scrollController.dispose();<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: _Background(<br>        scrollController: _scrollController,<br>        child: ListView.builder(<br>          controller: _scrollController,<br>          itemCount: ids.length,<br>          itemBuilder: (context, index) {<br>            final int id = ids[index];<br>            return ItemCard(id: id);<br>          },<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*TTpEWuLL_1374zPcDXsfsA.gif" /><figcaption>The result</figcaption></figure><h3>Conclusion</h3><p>Today we have learned how you can add parallax effect to your Flutter application with little effort.</p><p>Write in comments if you have ever added such an effect to your project and what tools you used.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b169a7bc386" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coloring SVG images in flutter, and why I decided to disable Impeller]]></title>
            <link>https://medium.com/@RuslanTsitser/coloring-svg-images-in-flutter-and-why-i-decided-to-disable-impeller-2f8a423f5316?source=rss-6114125bf8b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f8a423f5316</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ruslan Tsitser]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 22:28:45 GMT</pubDate>
            <atom:updated>2024-05-21T20:34:41.914Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to implement coloring SVG images in flutter</h3><p>Hi all, in <a href="https://medium.com/@cicerro96/how-to-implement-coloring-feature-in-flutter-using-chatgpt-005702edff1d">the previous article</a> <a href="https://medium.com/@cicerro96/how-to-implement-coloring-feature-in-flutter-using-chatgpt-005702edff1d">https://medium.com/@cicerro96/how-to-implement-coloring-feature-in-flutter-using-chatgpt-005702edff1d</a></p><p>I told you how to implement coloring for bitmap images, and today I will tell you how to do the same for vector images and how the choice of graphics engine can affect performance in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*WKw3_AcQC7mnlRw8.gif" /></figure><h3>Implementation of coloring</h3><p>The requirements are as follows:</p><ol><li>The vector picture is loaded by url</li><li>You can scale and move the picture</li><li>When you click on an area, it should be painted in the desired color</li></ol><h4>About vector images</h4><p>Before we get into the basic implementation, let’s remember what a vector image is.</p><p>SVG (Scalable Vector Graphics) is a vector graphics format used to describe images using XML-like tags. Vector images in SVG format scale well to any size without loss of quality, unlike raster images such as JPEG or PNG, which degrade in quality when enlarged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/0*AEsMULDMknvCqBpX.png" /></figure><p>If you look into the code of the SVG file representing the image above, you can see something like this:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;svg width=&quot;200&quot; height=&quot;200&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt;<br>  &lt;!-- Red rectangle with rounded corners --&gt;<br>  &lt;rect x=&quot;10&quot; y=&quot;10&quot; width=&quot;50&quot; height=&quot;50&quot; rx=&quot;10&quot; ry=&quot;10&quot; fill=&quot;red&quot; stroke=&quot;black&quot; stroke-width=&quot;2&quot;/&gt;<br><br>  &lt;!-- Blue circle --&gt;<br>  &lt;circle cx=&quot;100&quot; cy=&quot;50&quot; r=&quot;20&quot; fill=&quot;blue&quot; stroke=&quot;green&quot; stroke-width=&quot;3&quot;/&gt;<br><br>  &lt;!-- Yellow ellipse --&gt;<br>  &lt;ellipse cx=&quot;160&quot; cy=&quot;50&quot; rx=&quot;20&quot; ry=&quot;10&quot; fill=&quot;yellow&quot; stroke=&quot;pink&quot; stroke-width=&quot;2&quot;/&gt;<br><br>  &lt;!-- Black Line --&gt;<br>  &lt;line x1=&quot;10&quot; y1=&quot;100&quot; x2=&quot;50&quot; y2=&quot;150&quot; stroke=&quot;black&quot; stroke-width=&quot;4&quot;/&gt;<br><br>  &lt;!-- Polyline (broken line) --&gt;<br>  &lt;polyline points=&quot;60 100, 90 120, 120 100, 150 120&quot; stroke=&quot;orange&quot; stroke-width=&quot;2&quot; fill=&quot;none&quot;/&gt;<br><br>  &lt;!-- Polygon (closed shape) --&gt;<br>  &lt;polygon points=&quot;160 100, 190 120, 160 140, 130 120&quot; stroke=&quot;purple&quot; fill=&quot;lime&quot; stroke-width=&quot;1&quot;/&gt;<br><br>  &lt;!-- Path (complex figure) --&gt;<br>  &lt;path d=&quot;M10 160 Q 50 200, 90 160 T 170 160&quot; fill=&quot;none&quot; stroke=&quot;brown&quot; stroke-width=&quot;2&quot;/&gt;<br>&lt;/svg&gt;</pre><p>Here are:</p><ul><li><strong>XML declaration</strong>: Optional, indicates that the file is an XML file. For example: &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;.</li><li><strong>SVG tag</strong>: The root element that defines the space in which the graphic will be displayed. For example: <br>&lt;svg width=&quot;200&quot; height=&quot;200&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt; Sometimes this space can be specified as: <br>viewBox=&quot;0 0 200 200&quot;</li><li><strong>Graphics Elements</strong>: Inside the SVG tag are placed elements that describe the image. These can be:<br>Primitives (lines, circles, ellipses, rectangles, etc.): For example, &lt;rect x=&quot;10&quot; y=&quot;10&quot; width=&quot;50&quot; height=&quot;50&quot; rx=&quot;10&quot; ry=&quot;10&quot;/&gt; for a rectangle.<br>Paths (&lt;path&gt;): The most powerful SVG element describing complex shapes and curves.<br>Text (&lt;text&gt;): For adding text.<br>Groups (&lt;g&gt;): For grouping SVG elements together.</li><li><strong>Attributes</strong>: Define element properties such as coordinates, sizes, fill styles, stroke styles, and transformations. For example,fill=&quot;red&quot; sets the fill color to red.</li></ul><p>And many others. We will not focus on them.</p><p>You can see that the set of elements is very similar to the Canvas api in flutter, which is used in CustomPaint.</p><h4>Implementation</h4><p>For simplicity, in this case study we will consider pictures that have only closed paths as basic elements.</p><p><strong>Steps:</strong></p><ul><li>First, I created two classes: a VectorImage that will store all the elements of the picture and its size, a PathSvgItem that will store the Path path and the fill color Color? fill</li></ul><pre>// models.dart<br><br>import &#39;dart:ui&#39;;<br><br>class VectorImage {<br>  const VectorImage({<br>    required this.items,<br>    this.size,<br>  });<br><br>  final List&lt;PathSvgItem&gt; items;<br>  final Size? size;<br>}<br><br>class PathSvgItem {<br>  const PathSvgItem({<br>    required this.path,<br>    this.fill,<br>  });<br><br>  final Path path;<br>  final Color? fill;<br>}</pre><ul><li>Second, implement CustomPainter</li></ul><pre>// svg_painter.dart<br><br>import &#39;package:flutter/material.dart&#39;;<br><br>import &#39;models.dart&#39;;<br><br>class SvgPainter extends CustomPainter {<br>  const SvgPainter(this.pathSvgItem);<br>  final PathSvgItem pathSvgItem;<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    Path path = pathSvgItem.path;<br><br>    final paint = Paint();<br>    paint.color = pathSvgItem.fill ?? Colors.white;<br>    paint.style = PaintingStyle.fill;<br><br>    canvas.drawPath(path, paint);<br>  }<br><br>  @override<br>  bool shouldRepaint(SvgPainter oldDelegate) =&gt; false;<br>}</pre><ul><li>Get SVG file by url as a string:</li></ul><pre>// utils.dart<br><br>import &#39;package:http/http.dart&#39; as http;<br><br>Future&lt;String&gt; getSvgData(String url) async {<br>  final http.Response data = await http.get(Uri.parse(url));<br>  return data.body;<br>}</pre><ul><li><strong>Parsing of an SVG file</strong>. Knowing the approximate structure of the SVG file and using <a href="https://pub.dev/packages/xml">a library to read XML</a> files, we can pull out the elements and attributes. In the same file we can add the following:</li></ul><pre>// utils.dart<br><br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:path_drawing/path_drawing.dart&#39;;<br>import &#39;package:xml/xml.dart&#39;;<br><br>import &#39;models.dart&#39;;<br><br>VectorImage getVectorImageFromStringXml(String svgData) {<br>  List&lt;PathSvgItem&gt; items = [];<br><br>  // step 1: parse the xml<br>  XmlDocument document = XmlDocument.parse(svgData);<br><br>  // step 2: get the size of the svg<br>  Size? size;<br>  String? width = document.findAllElements(&#39;svg&#39;).first.getAttribute(&#39;width&#39;);<br>  String? height = document.findAllElements(&#39;svg&#39;).first.getAttribute(&#39;height&#39;);<br>  String? viewBox = document.findAllElements(&#39;svg&#39;).first.getAttribute(&#39;viewBox&#39;);<br>  if (width != null &amp;&amp; height != null) {<br>    width = width.replaceAll(RegExp(r&#39;[^0-9.]&#39;), &#39;&#39;);<br>    height = height.replaceAll(RegExp(r&#39;[^0-9.]&#39;), &#39;&#39;);<br>    size = Size(double.parse(width), double.parse(height));<br>  } else if (viewBox != null) {<br>    List&lt;String&gt; viewBoxList = viewBox.split(&#39; &#39;);<br>    size = Size(double.parse(viewBoxList[2]), double.parse(viewBoxList[3]));<br>  }<br><br>  // step 3: get the paths<br>  final List&lt;XmlElement&gt; paths = document.findAllElements(&#39;path&#39;).toList();<br>  for (int i = 0; i &lt; paths.length; i++) {<br>    final XmlElement element = paths[i];<br><br>    // get the path<br>    String? pathString = element.getAttribute(&#39;d&#39;);<br>    if (pathString == null) {<br>      continue;<br>    }<br>    Path path = parseSvgPathData(pathString);<br><br>    // get the fill color<br>    String? fill = element.getAttribute(&#39;fill&#39;);<br>    String? style = element.getAttribute(&#39;style&#39;);<br>    if (style != null) {<br>      fill = _getFillColor(style);<br>    }<br><br>    // get the transformations<br>    String? transformAttribute = element.getAttribute(&#39;transform&#39;);<br>    double scaleX = 1.0;<br>    double scaleY = 1.0;<br>    double? translateX;<br>    double? translateY;<br>    if (transformAttribute != null) {<br>      ({double x, double y})? scale = _getScale(transformAttribute);<br>      if (scale != null) {<br>        scaleX = scale.x;<br>        scaleY = scale.y;<br>      }<br>      ({double x, double y})? translate = _getTranslate(transformAttribute);<br>      if (translate != null) {<br>        translateX = translate.x;<br>        translateY = translate.y;<br>      }<br>    }<br><br>    final Matrix4 matrix4 = Matrix4.identity();<br>    if (translateX != null &amp;&amp; translateY != null) {<br>      matrix4.translate(translateX, translateY);<br>    }<br>    matrix4.scale(scaleX, scaleY);<br><br>    path = path.transform(matrix4.storage);<br><br>    items.add(PathSvgItem(<br>      fill: _getColorFromString(fill),<br>      path: path,<br>    ));<br>  }<br><br>  return VectorImage(items: items, size: size);<br>}<br><br>({double x, double y})? _getScale(String data) {<br>  RegExp regExp = RegExp(r&#39;scale\(([^,]+),([^)]+)\)&#39;);<br>  var match = regExp.firstMatch(data);<br><br>  if (match != null) {<br>    double scaleX = double.parse(match.group(1)!);<br>    double scaleY = double.parse(match.group(2)!);<br><br>    return (x: scaleX, y: scaleY);<br>  } else {<br>    return null;<br>  }<br>}<br><br>({double x, double y})? _getTranslate(String data) {<br>  RegExp regExp = RegExp(r&#39;translate\(([^,]+),([^)]+)\)&#39;);<br>  var match = regExp.firstMatch(data);<br><br>  if (match != null) {<br>    double translateX = double.parse(match.group(1)!);<br>    double translateY = double.parse(match.group(2)!);<br><br>    return (x: translateX, y: translateY);<br>  } else {<br>    return null;<br>  }<br>}<br><br>String? _getFillColor(String data) {<br>  RegExp regExp = RegExp(r&#39;fill:\s*(#[a-fA-F0-9]{6})&#39;);<br>  RegExpMatch? match = regExp.firstMatch(data);<br><br>  return match?.group(1);<br>}<br><br>Color _hexToColor(String hex) {<br>  final buffer = StringBuffer();<br>  if (hex.length == 6 || hex.length == 7) buffer.write(&#39;ff&#39;);<br>  buffer.write(hex.replaceFirst(&#39;#&#39;, &#39;&#39;));<br>  return Color(int.parse(buffer.toString(), radix: 16));<br>}<br><br>Color? _getColorFromString(String? colorString) {<br>  if (colorString == null) return null;<br>  if (colorString.startsWith(&#39;#&#39;)) {<br>    return _hexToColor(colorString);<br>  } else {<br>    switch (colorString) {<br>      case &#39;red&#39;:<br>        return Colors.red;<br>      case &#39;green&#39;:<br>        return Colors.green;<br>      case &#39;blue&#39;:<br>        return Colors.blue;<br>      case &#39;yellow&#39;:<br>        return Colors.yellow;<br>      case &#39;white&#39;:<br>        return Colors.white;<br>      case &#39;black&#39;:<br>        return Colors.black;<br>      default:<br>        return Colors.transparent;<br>    }<br>  }<br>}</pre><p>Because of the huge variety of attributes, you have to make such a mess of your own halpers. Not all cases are covered here, and I’m sure that some smart person has already made a library for all of them. But I didn’t find one and just used ChatGPT for boilerplate.</p><p><strong>What happens here is step-by-step, imperative, hardcore:</strong></p><ol><li>Parsing a string into an XML object from which we can pull the data we need</li><li>Determining the dimensions of the image, either through the given width and height, or through the viewBox</li><li>We also make the assumption that all the elements we need are represented as paths, if not, we skip it. To convert a string into a Path object, let’s use the path_drawing library method: Path parseSvgPathData(String svg);</li><li>For each element we get the necessary attributes:<br>- color, which can be in the form of a string “red”, “blue” or in the form of hex<br>- transformation. Without specifying this lines will be drawn from the coordinate (0;0) and in the wrong scale.</li><li>In the end the result is summarized into a pile and we get one VectorImage object as output</li></ol><p>If you want, you can add processing of attributes such as strokeWidth, strokeJoin, etc</p><ul><li>The result, you can pull to other places:</li></ul><pre>Future&lt;VectorImage&gt; getVectorImage(String url) async {<br>  final String svgData = await getSvgData(url);<br>  final VectorImage vectorImage = getVectorImageFromStringXml(svgData);<br>  return vectorImage;<br>}</pre><ul><li>Finally, let’s implement the screen itself to display the obtained picture:</li></ul><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:painter/features/coloring_svg/svg_painter.dart&#39;;<br><br>import &#39;models.dart&#39;;<br>import &#39;utils.dart&#39;;<br><br>class ColoringSvgScreen extends StatefulWidget {<br>  const ColoringSvgScreen({super.key});<br><br>  @override<br>  State&lt;ColoringSvgScreen&gt; createState() =&gt; _ColoringSvgScreenState();<br>}<br><br>class _ColoringSvgScreenState extends State&lt;ColoringSvgScreen&gt; {<br>  <br>  @override<br>  void initState() {<br>    _init();<br>    super.initState();<br>  }<br><br>  Size? _size;<br>  List&lt;PathSvgItem&gt;? _items;<br><br>  static const urlDogWithSmile =<br>      &#39;https://vk.com/doc223802256_674334116?hash=407AqZBhX6zQrqcI3cGxCZdJGaZDbv1ywq65EZ8eHqH&amp;dl=5KapGZXnEYzXOUUA977vWJoTB0kvZSrUzp7drp4qPIX&#39;;<br><br>  Future&lt;void&gt; _init() async {<br>    final value = await getVectorImage(urlDogWithSmile);<br>    setState(() {<br>      _items = value.items;<br>      _size = value.size;<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&#39;Coloring SVG&#39;)),<br>      body: _items == null || _size == null<br>          ? const Center(child: CircularProgressIndicator())<br>          : InteractiveViewer(<br>              child: Center(<br>                child: FittedBox(<br>                  // RepaintBoundary should be used to prevent rebuilds<br>                  // during transformations with InteractiveViewer<br>                  child: RepaintBoundary( <br>                    child: SizedBox(<br>                      width: _size!.width,<br>                      height: _size!.height,<br>                      child: Stack(<br>                        children: [<br>                          for (int index = 0; index &lt; _items!.length; index++)<br>                            SvgPainterImage(<br>                              item: _items![index],<br>                            )<br>                        ],<br>                      ),<br>                    ),<br>                  ),<br>                ),<br>              ),<br>            ),<br>    );<br>  }<br>}<br><br>class SvgPainterImage extends StatelessWidget {<br>  const SvgPainterImage({<br>    super.key,<br>    required this.item,<br>  });<br>  final PathSvgItem item;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return CustomPaint(<br>      painter: SvgPainter(item),<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*ps1e-rp0UHcvg98Y.gif" /><figcaption>scaling and translation</figcaption></figure><p>Thus, requirements 1 and 2 are met.</p><h4>How to catch which of the figures was tapped?</h4><p>CustomPainter has a method bool? hitTest(Offset position), that can be used for this purpose.</p><pre>class SvgPainter extends CustomPainter {<br>  const SvgPainter(this.pathSvgItem, this.onTap);<br>  final PathSvgItem pathSvgItem;<br>  final VoidCallback onTap;<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    Path path = pathSvgItem.path;<br><br>    final paint = Paint();<br>    paint.color = pathSvgItem.fill ?? Colors.white;<br>    paint.style = PaintingStyle.fill;<br><br>    canvas.drawPath(path, paint);<br>  }<br><br>  @override<br>  bool? hitTest(Offset position) {<br>    Path path = pathSvgItem.path;<br>    if (path.contains(position)) {<br>      onTap();<br>      return true;<br>    }<br>    return super.hitTest(position);<br>  }<br><br>  @override<br>  bool shouldRepaint(SvgPainter oldDelegate) {<br>    return pathSvgItem != oldDelegate.pathSvgItem;<br>  }<br>}</pre><ul><li>The onTap() callback is added here. It handles a tap if the Offset position is inside the Path pathoutline. It should also return true so that the hitTest() method is not triggered on widgets below in the stack. This is in case that path.contains(position) is truefor multiple PathSvgItem.</li><li>A condition has also been added to the shouldRepaint method when the widget should be redrawn.</li></ul><p>Updated code of ColoringSvgScreen widget:</p><pre>class ColoringSvgScreen extends StatefulWidget {<br>  const ColoringSvgScreen({super.key});<br><br>  @override<br>  State&lt;ColoringSvgScreen&gt; createState() =&gt; _ColoringSvgScreenState();<br>}<br><br>class _ColoringSvgScreenState extends State&lt;ColoringSvgScreen&gt; {<br>  @override<br>  void initState() {<br>    _init();<br>    super.initState();<br>  }<br><br>  Size? _size;<br>  List&lt;PathSvgItem&gt;? _items;<br><br>  static const urlDogWithSmile =<br>      &#39;https://vk.com/doc223802256_674334116?hash=407AqZBhX6zQrqcI3cGxCZdJGaZDbv1ywq65EZ8eHqH&amp;dl=5KapGZXnEYzXOUUA977vWJoTB0kvZSrUzp7drp4qPIX&#39;;<br><br>  Future&lt;void&gt; _init() async {<br>    final value = await getVectorImage(urlDogWithSmile);<br>    setState(() {<br>      _items = value.items;<br>      _size = value.size;<br>    });<br>  }<br><br>  void _onTap(int index) {<br>    setState(() {<br>      _items![index] = _items![index].copyWith(<br>        fill: Colors.red,<br>      );<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&#39;Coloring SVG&#39;)),<br>      body: _items == null || _size == null<br>          ? const Center(child: CircularProgressIndicator())<br>          : InteractiveViewer(<br>              child: Center(<br>                child: FittedBox(<br>                  // RepaintBoundary should be used to prevent rebuilds<br>                  // during transformations with InteractiveViewer<br>                  child: RepaintBoundary(<br>                    child: SizedBox(<br>                      width: _size!.width,<br>                      height: _size!.height,<br>                      child: Stack(<br>                        children: [<br>                          for (int index = 0; index &lt; _items!.length; index++)<br>                            SvgPainterImage(<br>                              item: _items![index],<br>                              size: _size!,<br>                              onTap: () =&gt; _onTap(index),<br>                            )<br>                        ],<br>                      ),<br>                    ),<br>                  ),<br>                ),<br>              ),<br>            ),<br>    );<br>  }<br>}<br><br>class SvgPainterImage extends StatelessWidget {<br>  const SvgPainterImage({<br>    super.key,<br>    required this.item,<br>    required this.size,<br>    required this.onTap,<br>  });<br>  final PathSvgItem item;<br>  final Size size;<br>  final VoidCallback onTap;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return CustomPaint(<br>      size: size,<br>      foregroundPainter: SvgPainter(item, onTap),<br>    );<br>  }<br>}</pre><ul><li>Added void _onTap(int index) method. There is implemented all the logic of color change in a specific PathSvgItem item. In the SvgPainterImage widget in the CustomPaint implementation, it is necessary to pass the Size size of the SVG image in order for hitTest() to work. Otherwise it will not work, because by default the widget size equals to Size.zero, and because of this it is actually impossible to hit the widget</li><li>Replaced painter with foregroundPainter. This was done because the previous version incorrectly processed the tap.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*GJkGzVFrSu6uNrKC.gif" /><figcaption>Result</figcaption></figure><p>We implemented coloring of a vector image. The example was a relatively simple image. But what if we try it on more complex and detailed images?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*IQMA5jvr8_-LTLYt.gif" /><figcaption>complex example</figcaption></figure><p>With this simple test, I found that having a large number of widgets on the screen made the performance poorer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ermS2gRvpYqRowdH.png" /><figcaption>Impeller</figcaption></figure><p>Tried a lot of things, but the strong difference in performance was discovered when I changed the graphics engine. The default from a certain version of flutter on iOS is Impeller, on Android this engine is still as an option. I set Skia as default for both platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IUCnCGf97k2erQYV.png" /><figcaption>Skia</figcaption></figure><p>This solved the issue with lags when moving the picture from side to side. But the issue remained open when scaling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*ukhLaToUHkgW9DPa.gif" /><figcaption>Scaling</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fw8zEldgDoiDd14k.png" /><figcaption>Skia</figcaption></figure><p>Then I decided to do it the tricky way, as described in <a href="https://medium.com/p/06b7bd93c44a">this article</a></p><ul><li>First, I made a painter that draws the ui.Image:</li></ul><pre>class ImagePainter extends CustomPainter {<br>  final ui.Image image;<br><br>  const ImagePainter(this.image);<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final paint = Paint();<br>    canvas.drawImage(image, Offset.zero, paint);<br>  }<br><br>  @override<br>  bool shouldRepaint(ImagePainter oldDelegate) =&gt; false;<br>}</pre><ul><li>Secondly, I implemented the logic of getting ui.Image by the GlobalKey:</li></ul><pre>  final GlobalKey _key = GlobalKey();<br>  bool _isInteraction = false;<br>  ui.Image? _image;<br><br>  void _onInteractionStart() {<br>    if (_isInteraction) return;<br>    _image = (_key.currentContext!.findRenderObject()! as RenderRepaintBoundary).toImageSync();<br>    setState(() {<br>      _isInteraction = true;<br>    });<br>  }<br><br>  void _onInteractionEnd() {<br>    if (!_isInteraction) return;<br>    setState(() {<br>      _isInteraction = false;<br>    });<br>    _image?.dispose();<br>    _image = null;<br>  }</pre><ul><li>Third, corrected the implementation in the build method of the main widget:</li></ul><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&#39;Coloring SVG&#39;)),<br>      body: _items == null || _size == null<br>          ? const Center(child: CircularProgressIndicator())<br>          : InteractiveViewer(<br>              onInteractionStart: (_) =&gt; _onInteractionStart(),<br>              onInteractionEnd: (_) =&gt; _onInteractionEnd(),<br>              child: Center(<br>                child: FittedBox(<br>                  child: _isInteraction<br>                      ? CustomPaint(<br>                          size: _size!,<br>                          painter: ImagePainter(_image!),<br>                        )<br>                      // RepaintBoundary should be used to prevent rebuilds<br>                      // during transformations with InteractiveViewer<br>                      : RepaintBoundary(<br>                          key: _key,<br>                          child: SizedBox(<br>                            width: _size!.width,<br>                            height: _size!.height,<br>                            child: Stack(<br>                              children: [<br>                                for (int index = 0; index &lt; _items!.length; index++)<br>                                  SvgPainterImage(<br>                                    item: _items![index],<br>                                    size: _size!,<br>                                    onTap: () =&gt; _onTap(index),<br>                                  )<br>                              ],<br>                            ),<br>                          ),<br>                        ),<br>                ),<br>              ),<br>            ),<br>    );<br>  }</pre><p>Thus, we rotate and move not a heavy RenderObject, but a bitmap. This action should be easier for both engines:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mS5xHM1wjb3D142O.png" /><figcaption>Skia</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9CTp38SkZVeyeuCerrxyQA.png" /><figcaption>Impeller</figcaption></figure><h3>Conclusion</h3><p>We have implemented coloring of vector images and tested the performance with different situations. We found out that the new Impeller engine is inferior to Skia in cases when you need to display a large number of widgets on the screen. Sometimes you can get around this barrier, as the example showed, by manipulating the bitmap image rather than the widget itself. But, unfortunately, it doesn’t always work that way, and in some of my projects I have given up using Impeller as the main graphics engine.</p><p>I hope that the material of this article will help you to optimize UI in your projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f8a423f5316" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement coloring feature in flutter using ChatGPT]]></title>
            <link>https://medium.com/@RuslanTsitser/how-to-implement-coloring-feature-in-flutter-using-chatgpt-005702edff1d?source=rss-6114125bf8b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/005702edff1d</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ruslan Tsitser]]></dc:creator>
            <pubDate>Wed, 07 Feb 2024 11:13:57 GMT</pubDate>
            <atom:updated>2024-02-17T14:40:01.057Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to implement coloring feature in flutter app using ChatGPT</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V2aht7XBFM6iBqG8.png" /></figure><p>Hello everyone. As I told you earlier in my articles, I like to do applications for entertainment. And recently there was a task — to implement a feature with coloring of images. Today we will look at how to implement such coloring for bitmap images using flood fill algorithm. We will see what we already have on pub.dev, look into the theory of this algorithm, implement it on dart using ChatGPT and apply it in flutter application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*3UAkuOWLDPPzCvd1r8txyg.gif" /></figure><h3>Research in pub.dev</h3><p>There is already a <a href="https://pub.dev/packages/floodfill_image">floodfill_image</a> library on pub.dev that provides options for colorizing png and jpg images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*kDFjl02xQfBU1ThE.gif" /></figure><p><strong>Available features:</strong><br>1) Downloading a picture from the Internet and from assets<br>2) Selecting a color to paint<br>3) Selecting colors that will not be repainted<br>4) You can specify tolerance, that is, which neighboring colors should also paint if they are slightly different in hue<br>5) Optional: callbacks that can be used to save the progress of coloring, and a placeholder widget for downloading.</p><p><strong>Pros:</strong><br>1) Supported by all platforms<br>2) Easy to use</p><p><strong>Disadvantages of the current implementation:</strong><br>1) The first thing I noticed was the inability to set a higher sensitivity. Because of the low tolerance, white unpainted areas appear next to contours (you can see on the gif)<br>2) The quality of the image is lost a lot, and there is no way to affect it without changing the library itself<br>3) The library has not been updated for more than 2 years. At the time of writing, the library version is 0.0.8.</p><p>On the one hand, this is good: if there are no conflicts with new versions of the framework and the library fulfills its tasks, then it was written well. But on the other hand, the code has a tendency to become outdated. The rules and style that were relevant then, now make it less and less understandable.</p><p>This raises the question — to correct the existing implementation in the library by digging into someone else’s code or to write your own workarounds.</p><p>And I chose the first option at first. I won’t go into details on how to make a fork and pull up the library by url, as this is material for other articles. I will only say that I faced typical problems: linter swears, my hands itch to refactor everything you see.</p><p>In the end, with small losses I achieved the first two goals: to correct tolerance and to improve quality.</p><p>And that’s a good place to stop, since the task has been accomplished.</p><p>Now let’s imagine that there is no ready implementation of the algorithm on flutter, but there is Google, Wikipedia and ChatGPT</p><h3>What is the flood fill algorithm?</h3><p>To answer this question, I did what I did in my college days — I googled and found the answer in Wikipedia. It says:</p><blockquote><strong>Flood fill</strong>, also called <strong>seed fill</strong>, is a <a href="https://en.wikipedia.org/wiki/Flooding_algorithm">flooding algorithm</a> that determines and alters the area <a href="https://en.wikipedia.org/wiki/Glossary_of_graph_theory#Connectivity">connected</a> to a given node in a multi-dimensional <a href="https://en.wikipedia.org/wiki/Array_data_structure">array</a> with some matching attribute. It is used in the “bucket” fill tool of <a href="https://en.wikipedia.org/wiki/Paint_program">paint programs</a> to fill connected, similarly-colored areas with a different color, and in games such as <a href="https://en.wikipedia.org/wiki/Go_(game)">Go</a> and <a href="https://en.wikipedia.org/wiki/Minesweeper_(video_game)">Minesweeper</a> for determining which pieces are cleared. A variant called <strong>boundary fill</strong> uses the same algorithms but is defined as the area <a href="https://en.wikipedia.org/wiki/Glossary_of_graph_theory#Connectivity">connected</a> to a given node that does not have a particular attribute.</blockquote><p>There’s nothing special about it. It’s just a name for an algorithm that is used when changing the area of values in a multidimensional array.</p><p>Wikipedia gives 4 examples of algorithm implementation:</p><ol><li>Stack-based recursive implementation (four-way)</li><li>Span filling</li><li>Graph-theoretic filling</li><li>Walk-based filling (Fixed-memory method).</li></ol><p>In the classical version of the algorithm we need a two-dimensional array, a coordinate, the current value in the specified coordinate and a new value, which will also replace the neighboring values if they are equal to the value in the current coordinate.</p><p>Before we start implementing the algorithm, let’s write what should be the common interface for all implementations:</p><pre>abstract class FloodFill {<br>  final List&lt;List&lt;int&gt;&gt; image;<br>  const FloodFill(this.image);<br>  void fill(int startX, int startY, int newColor);<br>}</pre><h4>Stack-based recursive implementation</h4><p>The easiest to understand and implement, in my opinion, is the first variant, where recursion is used. The logic is simple — we check a pixel, and then the neighboring ones, and so on, until we pass through all the pixels that satisfy certain conditions. This is how the algorithm looks like if we use recursion directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*W0XiCeqz3IQ0A9i3Cz7ITw.png" /></figure><p>I asked ChatGPT to write an implementation of the recursive flood fill algorithm on Dart:</p><blockquote>Write me an implementation of this algorithm for dart language:<br>Flood-fill (node): <br>If node is not Inside return. <br>Set the node <br>Perform Flood-fill one step to the south of node. <br>Perform Flood-fill one step to the north of node <br>Perform Flood-fill one step to the west of node <br>Perform Flood-fill one step to the east of node <br>Return.</blockquote><blockquote>use such interface:</blockquote><blockquote>abstract class FloodFill {<br> final List&lt;List&lt;int&gt;&gt; image;<br> const FloodFill(this.image);<br> void fill(int startX, int startY, int newColor);<br> }</blockquote><p>And he returned this code:</p><pre>class BasicFloodFill extends FloodFill {<br> const BasicFloodFill(List&lt;List&lt;int&gt;&gt; image) : super(image);<br><br>  @override<br>  void fill(int startX, int startY, int newColor) {<br>    int originalColor = image[startX][startY];<br>    _floodFillUtil(startX, startY, originalColor, newColor);<br>  }<br><br>  void _floodFillUtil(int x, int y, int originalColor, int newColor) {<br>    // Check if current node is inside the boundary and not already filled<br>    if (!_isInside(x, y) || image[x][y] != originalColor) return;<br><br>    // Set the node<br>    image[x][y] = newColor;<br><br>    // Perform flood-fill one step in each direction<br>    _floodFillUtil(x + 1, y, originalColor, newColor); // South<br>    _floodFillUtil(x - 1, y, originalColor, newColor); // North<br>    _floodFillUtil(x, y - 1, originalColor, newColor); // West<br>    _floodFillUtil(x, y + 1, originalColor, newColor); // East<br>  }<br><br>  bool _isInside(int x, int y) {<br>    return x &gt;= 0 &amp;&amp; x &lt; image.length &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; image[0].length;<br>  }<br>}</pre><p>Then asked for the same recursive algorithm, but using data structures:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7kTTc--zzkRvDZp1.png" /></figure><blockquote>Write me an implementation of this algorithm for dart language: <br>Flood-fill (node): <br>Set Q to the empty queue or stack. <br>Add node to the end of Q. <br>While Q is not empty: <br>Set n equal to the first element of Q. <br>Remove first element from Q. <br>If n is Inside: <br>Set the n <br>Add the node to the west of n to the end of Q. <br>Add the node to the east of n to the end of Q. <br>Add the node to the north of n to the end of Q. <br>Add the node to the south of n to the end of Q. <br>Continue looping until Q is exhausted. <br>Return.</blockquote><blockquote>Use such interface:<br>abstract class FloodFill {<br> final List&lt;List&lt;int&gt;&gt; image;<br> const FloodFill(this.image);<br> void fill(int startX, int startY, int newColor);<br> }</blockquote><p>The result is:</p><pre>import &#39;dart:collection&#39;;<br><br>class Point {<br>  final int x;<br>  final int y;<br><br>  const Point(this.x, this.y);<br>}<br><br>class FloodFillQueueImpl extends FloodFill {<br>  const FloodFillQueueImpl(List&lt;List&lt;int&gt;&gt; image) : super(image);<br><br>  @override<br>  void fill(int startX, int startY, int newColor) {<br>    final int oldColor = image[startX][startY];<br>    final Queue&lt;Point&gt; queue = Queue();<br>    queue.add(Point(startY, startX));<br><br>    while (queue.isNotEmpty) {<br>      final Point point = queue.removeFirst();<br>      final int x = point.x;<br>      final int y = point.y;<br><br>      if (image[y][x] == oldColor) {<br>        image[y][x] = newColor;<br><br>        if (x &gt; 0) {<br>          queue.add(Point(x - 1, y));<br>        }<br>        if (x &lt; image[y].length - 1) {<br>          queue.add(Point(x + 1, y));<br>        }<br>        if (y &gt; 0) {<br>          queue.add(Point(x, y - 1));<br>        }<br>        if (y &lt; image.length - 1) {<br>          queue.add(Point(x, y + 1));<br>        }<br>      }<br>    }<br>  }<br>}</pre><h4>Span filling</h4><p>This algorithm works by sequentially considering the horizontal lines of the image and filling in the areas between the intersections of these lines with the edges of the region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wde9W4iE3g6FPCQa.png" /></figure><blockquote>Write me an implementation of this algorithm for dart language: <br>fn fill(x, y): <br>if not Inside(x, y) then return <br>let s = new empty queue or stack <br>Add (x, x, y, 1) to s <br>Add (x, x, y — 1, -1) to s <br>while s is not empty: <br>Remove an (x1, x2, y, dy) from s <br>let x = x1 <br>if Inside(x, y): <br>while Inside(x — 1, y): <br>Set(x — 1, y) <br>x = x — 1 <br>if x &lt; x1: <br>Add (x, x1–1, y — dy, -dy) to s <br>while x1 &lt;= x2: <br>while Inside(x1, y): <br>Set(x1, y) <br>x1 = x1 + 1 <br>if x1 &gt; x: <br>Add (x, x1–1, y + dy, dy) to s <br>if x1–1 &gt; x2: <br>Add (x2 + 1, x1–1, y — dy, -dy) to s <br>x1 = x1 + 1 <br>while x1 &lt; x2 and not Inside(x1, y): <br>x1 = x1 + 1 <br>x = x1</blockquote><blockquote>Use such interface: <br>abstract class abstract class FloodFill {<br> final List&lt;List&lt;int&gt;&gt; image;<br> const FloodFill(this.image);<br> void fill(int startX, int startY, int newColor);<br> }</blockquote><pre>class FloodFillSpanImpl extends FloodFill {<br>  const FloodFillSpanImpl(List&lt;List&lt;int&gt;&gt; image) : super(image);<br><br>  // Check if the point is inside the canvas and matches the target color<br>  bool _isInside(int x, int y, int targetColor) {<br>    return x &gt;= 0 &amp;&amp; y &gt;= 0 &amp;&amp; x &lt; image.length &amp;&amp; y &lt; image[0].length &amp;&amp; image[x][y] == targetColor;<br>  }<br><br>  // Set a point to the replacement color<br>  void _setColor(int x, int y, int replacementColor) {<br>    image[x][y] = replacementColor;<br>  }<br><br>  @override<br>  void fill(int startX, int startY, int newColor) {<br>    final targetColor = image[startX][startY];<br><br>    if (!_isInside(startX, startY, targetColor)) return;<br><br>    var s = &lt;List&lt;int&gt;&gt;[];<br>    s.add([startX, startX, startY, 1]);<br>    s.add([startX, startX, startY - 1, -1]);<br><br>    while (s.isNotEmpty) {<br>      var tuple = s.removeLast();<br>      var x1 = tuple[0];<br>      var x2 = tuple[1];<br>      var y = tuple[2];<br>      var dy = tuple[3];<br><br>      var nx = x1;<br>      if (_isInside(nx, y, targetColor)) {<br>        while (_isInside(nx - 1, y, targetColor)) {<br>          _setColor(nx - 1, y, newColor);<br>          nx--;<br>        }<br>        if (nx &lt; x1) {<br>          s.add([nx, x1 - 1, y - dy, -dy]);<br>        }<br>      }<br><br>      while (x1 &lt;= x2) {<br>        while (_isInside(x1, y, targetColor)) {<br>          _setColor(x1, y, newColor);<br>          x1++;<br>        }<br>        if (x1 &gt; nx) {<br>          s.add([nx, x1 - 1, y + dy, dy]);<br>        }<br>        if (x1 - 1 &gt; x2) {<br>          s.add([x2 + 1, x1 - 1, y - dy, -dy]);<br>        }<br>        x1++;<br>        while (x1 &lt; x2 &amp;&amp; !_isInside(x1, y, targetColor)) {<br>          x1++;<br>        }<br>        nx = x1;<br>      }<br>    }<br>  }<br>}</pre><p>We won’t consider the other implementations, because <strong>Graph-theoretic filling</strong> doesn’t have a worded implementation like the previous variants, and I don’t really want to go into details. And in the disadvantages of the <strong>Walk-based filling</strong> algorithm it is written that it can spend a lot of time in cycles before it finishes.</p><p>Since there is a common interface, we can run small tests. We will compare the result and, just in case, the execution speed:</p><pre>import &#39;package:flutter_test/flutter_test.dart&#39;;<br>import &#39;package:painter/features/examples/algorithms.dart&#39;;<br><br>void main() {<br>  group(<br>    &#39;FloodFill classic&#39;,<br>    () {<br>      test(&#39;grid 30x30&#39;, () {<br>        final Stopwatch stopwatch = Stopwatch()..start();<br><br>        List&lt;List&lt;int&gt;&gt; image = [<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 3, 3, 3, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 3, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],<br>        ];<br><br>        BasicFloodFill(image).fill(7, 8, 2);<br><br>        stopwatch.stop();<br>        print(&#39;Elapsed time: ${stopwatch.elapsed}&#39;);<br><br>        List&lt;List&lt;int&gt;&gt; result = [<br>          [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 2, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 3, 0, 3, 3, 3, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 3, 0, 0, 0, 0, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 3, 0, 0, 0, 0, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 3, 0, 0, 0, 0, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 3, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],<br>        ];<br>        expect(image, result);<br>      });<br>    },<br>  );<br>  group(<br>    &#39;FloodFill queued&#39;,<br>    () {<br>      test(&#39;grid 30x30&#39;, () {<br>        final Stopwatch stopwatch = Stopwatch()..start();<br><br>        List&lt;List&lt;int&gt;&gt; image = [<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 3, 3, 3, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 3, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],<br>        ];<br><br>        FloodFillQueueImpl(image).fill(7, 8, 2);<br><br>        stopwatch.stop();<br>        print(&#39;Elapsed time: ${stopwatch.elapsed}&#39;);<br>        List&lt;List&lt;int&gt;&gt; result = [<br>          [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 2, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 3, 0, 3, 3, 3, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 3, 0, 0, 0, 0, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 3, 0, 0, 0, 0, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 3, 0, 0, 0, 0, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 3, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],<br>        ];<br>        expect(image, result);<br>      });<br>    },<br>  );<br>  group(<br>    &#39;FloodFill span&#39;,<br>    () {<br>      test(&#39;grid 30x30&#39;, () {<br>        final Stopwatch stopwatch = Stopwatch()..start();<br><br>        List&lt;List&lt;int&gt;&gt; image = [<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 3, 3, 3, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 3, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],<br>        ];<br>        final floodFill = FloodFillSpanImpl(image);<br>        floodFill.fill(7, 8, 2);<br><br>        stopwatch.stop();<br>        print(&#39;Elapsed time: ${stopwatch.elapsed}&#39;);<br><br>        List&lt;List&lt;int&gt;&gt; result = [<br>          [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 2, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 3, 0, 3, 3, 3, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 3, 0, 0, 0, 0, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 3, 0, 0, 0, 0, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 3, 0, 0, 0, 0, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 3, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2],<br>          [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],<br>        ];<br>        expect(image, result);<br>      });<br>    },<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/0*J4Xj5WOkU37rqF72.png" /><figcaption>image in the numbers</figcaption></figure><p>The results of running several tests +- are as follows:</p><pre>00:01 +0: FloodFill classic grid 30x30                                                                                                                   <br>Elapsed time: 0:00:00.000300<br>00:01 +1: FloodFill queued grid 30x30                                                                                                                    <br>Elapsed time: 0:00:00.000864<br>00:01 +2: FloodFill span grid 30x30                                                                                                                      <br>Elapsed time: 0:00:00.000338<br>00:01 +3: All tests passed!  </pre><p>Hence the conclusion that either ChatGPT implemented the algorithms crookedly, or the second implementation (recursion with queues) is really much slower, and the leader is ordinary recursion.</p><h3>Implementation in the context of a flutter application</h3><h4>Interface</h4><p>First, let’s figure out what kind of interface we want to have for coloring real images. Let’s use the previous option by adding generics:</p><pre>abstract class FloodFill&lt;T, S&gt; {<br>  final T image;<br>  const FloodFill(this.image);<br>  void fill(int startX, int startY, S newColor);<br>}</pre><h4>Helpers</h4><p>Since we will be using the standard dart:ui library, we need to add a few helper methods to work with it.</p><p>First, this library does not have the ability to interact with individual pixels of an image directly. Therefore, we need transformations into such a data structure to make this possibility appear. Bytes are suitable for this purpose. Let’s realize transformations in both directions:</p><pre>import &#39;dart:async&#39;;<br>import &#39;dart:typed_data&#39;;<br>import &#39;dart:ui&#39; as ui;<br><br>Future&lt;ByteData?&gt; imageToBytes(ui.Image image) async {<br>  final bytes = await image.toByteData(format: ui.ImageByteFormat.rawRgba);<br>  return bytes;<br>}<br><br>Future&lt;ui.Image&gt; imageFromBytes(ByteData bytes, int imageWidth, int imageHeight) {<br>  final Completer&lt;ui.Image&gt; completer = Completer();<br>  ui.decodeImageFromPixels(<br>    bytes.buffer.asUint8List(),<br>    imageWidth,<br>    imageHeight,<br>    ui.PixelFormat.rgba8888,<br>    (img) {<br>      completer.complete(img);<br>    },<br>  );<br>  return completer.future;<br>}</pre><p>Second, we can’t specify color directly in bytes either, so it too requires conversion to bytes and back.</p><p>A colored pixel can be represented as a combination of red <strong>R</strong>, green <strong>G</strong>, and blue <strong>B</strong> colors of different shades. A fourth alpha <strong>A</strong>, or transparency, is often added to this mix as well.</p><p>Different shades of color can be encoded using combinations of 0 and 1 (one bit). It is customary to encode them using 8 bits (2⁸ = 256 different variations), or one byte. Thus, one color, if it is a combination of RGBA, can be represented as a sequence of 8x4=32 zeros or ones, or 32 bits, or 4 bytes. Accordingly, in a byte array from a picture, each pixel follows each other through 4.</p><p>In the code above, the image is converted to bytes, where colors are represented in RGBA format, while Color in the dart:ui library stores the value in ARGB format by default. This should definitely be taken into account:</p><pre>void setPixelColor({<br>  required int x,<br>  required int y,<br>  required ByteData bytes,<br>  <br>  // for correct representation of color bytes&#39; coordinates <br>  // in an array of image bytes<br>  required int imageWidth,  <br>  required ui.Color newColor,<br>}) {<br>  bytes.setUint32(<br>    (x + y * imageWidth) * 4, // offset<br>    colorToIntRGBA(newColor), // value<br>  );<br>}<br><br>ui.Color getPixelColor({<br>  required ByteData bytes,<br>  required int x,<br>  required int y,<br>  required int imageWidth,<br>}) {<br>  final uint32 = bytes.getUint32((x + y * imageWidth) * 4);<br>  return colorFromIntRGBA(uint32);<br>}<br><br>int colorToIntRGBA(ui.Color color) {<br>  // Extract ARGB components<br>  int a = (color.value &gt;&gt; 24) &amp; 0xFF;<br>  int r = (color.value &gt;&gt; 16) &amp; 0xFF;<br>  int g = (color.value &gt;&gt; 8) &amp; 0xFF;<br>  int b = color.value &amp; 0xFF;<br><br>  // Convert to RGBA and combine into a single integer<br>  return (r &lt;&lt; 24) | (g &lt;&lt; 16) | (b &lt;&lt; 8) | a;<br>}<br><br>ui.Color colorFromIntRGBA(int uint32Rgba) {<br>  // Extract RGBA components<br>  int r = (uint32Rgba &gt;&gt; 24) &amp; 0xFF;<br>  int g = (uint32Rgba &gt;&gt; 16) &amp; 0xFF;<br>  int b = (uint32Rgba &gt;&gt; 8) &amp; 0xFF;<br>  int a = uint32Rgba &amp; 0xFF;<br><br>  // Convert to ARGB format and create a Color object<br>  return ui.Color.fromARGB(a, r, g, b);<br>}</pre><p>Third, a helper that allows you to compare almost similar colors, that is, in essence, you can pass sensitivity here, as in the library discussed at the beginning. I have set the default value threshold = 50:</p><pre>bool isAlmostSameColor({<br>  required ui.Color pixelColor,<br>  required ui.Color checkColor,<br>  required int imageWidth,<br>}) {<br>  const int threshold = 50;<br>  final int rDiff = (pixelColor.red - checkColor.red).abs();<br>  final int gDiff = (pixelColor.green - checkColor.green).abs();<br>  final int bDiff = (pixelColor.blue - checkColor.blue).abs();<br>  return rDiff &lt; threshold &amp;&amp; gDiff &lt; threshold &amp;&amp; bDiff &lt; threshold;<br>}</pre><h4>Algorithm implementation</h4><p>Since there are asynchronous transformations, the method that was in the FloodFill class earlier is not quite suitable anymore, so let’s make another upgrade:</p><pre>abstract class FloodFill&lt;T, S&gt; {<br>  final T image;<br>  const FloodFill(this.image);<br>  FutureOr&lt;T?&gt; fill(int startX, int startY, S newColor);<br>}</pre><p>In this variant, the fill() method can return the result of T? image either asynchronously or synchronously, depending on the implementation. So, let’s upgrade code:</p><pre>class BasicFloodFill extends FloodFill&lt;List&lt;List&lt;int&gt;&gt;, int&gt; {<br>  const BasicFloodFill(List&lt;List&lt;int&gt;&gt; image) : super(image);<br><br>  @override<br>  List&lt;List&lt;int&gt;&gt;? fill(int startX, int startY, int newColor) {<br>    int originalColor = image[startX][startY];<br>    _floodFillUtil(startX, startY, originalColor, newColor);<br>    return image;<br>  }<br><br>  void _floodFillUtil(int x, int y, int originalColor, int newColor) {<br>    // Check if current node is inside the boundary and not already filled<br>    if (!_isInside(x, y) || image[x][y] != originalColor) return;<br><br>    // Set the node<br>    image[x][y] = newColor;<br><br>    // Perform flood-fill one step in each direction<br>    _floodFillUtil(x + 1, y, originalColor, newColor); // South<br>    _floodFillUtil(x - 1, y, originalColor, newColor); // North<br>    _floodFillUtil(x, y - 1, originalColor, newColor); // West<br>    _floodFillUtil(x, y + 1, originalColor, newColor); // East<br>  }<br><br>  bool _isInside(int x, int y) {<br>    return x &gt;= 0 &amp;&amp; x &lt; image.length &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; image[0].length;<br>  }<br>}<br><br>class Point {<br>  final int x;<br>  final int y;<br><br>  const Point(this.x, this.y);<br>}<br><br>class FloodFillQueueImpl extends FloodFill&lt;List&lt;List&lt;int&gt;&gt;, int&gt; {<br>  const FloodFillQueueImpl(List&lt;List&lt;int&gt;&gt; image) : super(image);<br><br>  @override<br>  List&lt;List&lt;int&gt;&gt;? fill(int startX, int startY, int newColor) {<br>    final int oldColor = image[startX][startY];<br>    final int width = image[0].length;<br>    final int height = image.length;<br>    final Queue&lt;Point&gt; queue = Queue();<br>    queue.add(Point(startY, startX));<br><br>    while (queue.isNotEmpty) {<br>      final Point point = queue.removeFirst();<br>      final int x = point.x;<br>      final int y = point.y;<br><br>      if (image[y][x] == oldColor) {<br>        image[y][x] = newColor;<br><br>        if (x &gt; 0) {<br>          queue.add(Point(x - 1, y));<br>        }<br>        if (x &lt; width - 1) {<br>          queue.add(Point(x + 1, y));<br>        }<br>        if (y &gt; 0) {<br>          queue.add(Point(x, y - 1));<br>        }<br>        if (y &lt; height - 1) {<br>          queue.add(Point(x, y + 1));<br>        }<br>      }<br>    }<br>    return image;<br>  }<br>}<br><br>class FloodFillSpanImpl extends FloodFill&lt;List&lt;List&lt;int&gt;&gt;, int&gt; {<br>  const FloodFillSpanImpl(List&lt;List&lt;int&gt;&gt; image) : super(image);<br><br>  // Check if the point is inside the canvas and matches the target color<br>  bool _isInside(int x, int y, int targetColor) {<br>    return x &gt;= 0 &amp;&amp; y &gt;= 0 &amp;&amp; x &lt; image.length &amp;&amp; y &lt; image[0].length &amp;&amp; image[x][y] == targetColor;<br>  }<br><br>  // Set a point to the replacement color<br>  void _setColor(int x, int y, int replacementColor) {<br>    image[x][y] = replacementColor;<br>  }<br><br>  @override<br>  List&lt;List&lt;int&gt;&gt;? fill(int startX, int startY, int newColor) {<br>    final targetColor = image[startX][startY];<br><br>    if (!_isInside(startX, startY, targetColor)) return null;<br><br>    var s = &lt;List&lt;int&gt;&gt;[];<br>    s.add([startX, startX, startY, 1]);<br>    s.add([startX, startX, startY - 1, -1]);<br><br>    while (s.isNotEmpty) {<br>      var tuple = s.removeLast();<br>      var x1 = tuple[0];<br>      var x2 = tuple[1];<br>      var y = tuple[2];<br>      var dy = tuple[3];<br><br>      var nx = x1;<br>      if (_isInside(nx, y, targetColor)) {<br>        while (_isInside(nx - 1, y, targetColor)) {<br>          _setColor(nx - 1, y, newColor);<br>          nx--;<br>        }<br>        if (nx &lt; x1) {<br>          s.add([nx, x1 - 1, y - dy, -dy]);<br>        }<br>      }<br><br>      while (x1 &lt;= x2) {<br>        while (_isInside(x1, y, targetColor)) {<br>          _setColor(x1, y, newColor);<br>          x1++;<br>        }<br>        if (x1 &gt; nx) {<br>          s.add([nx, x1 - 1, y + dy, dy]);<br>        }<br>        if (x1 - 1 &gt; x2) {<br>          s.add([x2 + 1, x1 - 1, y - dy, -dy]);<br>        }<br>        x1++;<br>        while (x1 &lt; x2 &amp;&amp; !_isInside(x1, y, targetColor)) {<br>          x1++;<br>        }<br>        nx = x1;<br>      }<br>    }<br>    return image;<br>  }<br>}</pre><p>Let’s ask ChatGPT to implement the algorithm:</p><blockquote>I have this interface<br> abstract class FloodFill&lt;T, S&gt; {<br> final T image;<br> const FloodFill(this.image);<br> FutureOr&lt;T?&gt; fill(int startX, int startY, S newColor);<br> }</blockquote><blockquote>I need you to upgrade an implementation below for the new values:</blockquote><blockquote>class BasicFloodFill extends FloodFill&lt;List&lt;List&lt;int&gt;&gt;, int&gt; {<br> const BasicFloodFill(List&lt;List&lt;int&gt;&gt; image) : super(image);</blockquote><blockquote>@override<br> List&lt;List&lt;int&gt;&gt;? fill(int startX, int startY, int newColor) {<br> int originalColor = image[startX][startY];<br> _floodFillUtil(startX, startY, originalColor, newColor);<br> return image;<br> }</blockquote><blockquote>void _floodFillUtil(int x, int y, int originalColor, int newColor) {<br> // Check if current node is inside the boundary and not already filled<br> if (!_isInside(x, y) || image[x][y] != originalColor) return;</blockquote><blockquote>// Set the node<br> image[x][y] = newColor;</blockquote><blockquote>// Perform flood-fill one step in each direction<br> _floodFillUtil(x + 1, y, originalColor, newColor); // South<br> _floodFillUtil(x — 1, y, originalColor, newColor); // North<br> _floodFillUtil(x, y — 1, originalColor, newColor); // West<br> _floodFillUtil(x, y + 1, originalColor, newColor); // East</blockquote><blockquote>bool _isInside(int x, int y) {<br> return x &gt;= 0 &amp;&amp; x &lt; image.length &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; image[0].length;<br> }<br> }</blockquote><blockquote>Where T is an ui.Image from the library dart:ui as ui, and S is an ui.Color also from this library.</blockquote><blockquote>Please, use these helpers:</blockquote><blockquote>Future&lt;ByteData?&gt; imageToBytes(ui.Image image) async {<br> final bytes = await image.toByteData(format: ui.ImageByteFormat.rawRgba);<br> return bytes;<br> }</blockquote><blockquote>Future&lt;ui.Image&gt; imageFromBytes(ByteData bytes, int imageWidth, int imageHeight) {<br> final Completer&lt;ui.Image&gt; completer = Completer();<br> ui.decodeImageFromPixels(<br> bytes.buffer.asUint8List(),<br> imageWidth,<br> imageHeight,<br> ui.PixelFormat.rgba8888,<br> (img) {<br> completer.complete(img);<br> },<br> );<br> return completer.future;<br> }</blockquote><blockquote>bool isAlmostSameColor({<br> required ui.Color pixelColor,<br> required ui.Color checkColor,<br> required int imageWidth,<br> }) {<br> const int threshold = 50;<br> final int rDiff = (pixelColor.red — checkColor.red).abs();<br> final int gDiff = (pixelColor.green — checkColor.green).abs();<br> final int bDiff = (pixelColor.blue — checkColor.blue).abs();<br> return rDiff &lt; threshold &amp;&amp; gDiff &lt; threshold &amp;&amp; bDiff &lt; threshold;<br> }</blockquote><blockquote>void setPixelColor({<br> required int x,<br> required int y,<br> required ByteData bytes,<br> required int imageWidth,<br> required ui.Color newColor,<br> }) {<br> bytes.setUint32(<br> (x + y * imageWidth) * 4,<br> colorToIntRGBA(newColor),<br> );<br> }</blockquote><blockquote>ui.Color getPixelColor({<br> required ByteData bytes,<br> required int x,<br> required int y,<br> required int imageWidth,<br> }) {<br> final uint32 = bytes.getUint32((x + y * imageWidth) * 4);<br> return colorFromIntRGBA(uint32);<br> }</blockquote><blockquote>int colorToIntRGBA(ui.Color color) {<br> // Extract ARGB components<br> int a = (color.value &gt;&gt; 24) &amp; 0xFF;<br> int r = (color.value &gt;&gt; 16) &amp; 0xFF;<br> int g = (color.value &gt;&gt; 8) &amp; 0xFF;<br> int b = color.value &amp; 0xFF;</blockquote><blockquote>// Convert to RGBA and combine into a single integer<br> return (r &lt;&lt; 24) | (g &lt;&lt; 16) | (b &lt;&lt; 8) | a;<br> }</blockquote><blockquote>ui.Color colorFromIntRGBA(int uint32Rgba) {<br> // Extract RGBA components<br> int r = (uint32Rgba &gt;&gt; 24) &amp; 0xFF;<br> int g = (uint32Rgba &gt;&gt; 16) &amp; 0xFF;<br> int b = (uint32Rgba &gt;&gt; 8) &amp; 0xFF;<br> int a = uint32Rgba &amp; 0xFF;</blockquote><blockquote>// Convert to ARGB format and create a Color object<br> return ui.Color.fromARGB(a, r, g, b);<br> }</blockquote><p>The result is:</p><pre>import &#39;dart:async&#39;;<br>import &#39;dart:typed_data&#39;;<br>import &#39;dart:ui&#39; as ui;<br><br>class ImageFloodFill extends FloodFill&lt;ui.Image, ui.Color&gt; {<br>  ImageFloodFill(ui.Image image) : super(image);<br><br>  @override<br>  Future&lt;ui.Image?&gt; fill(int startX, int startY, ui.Color newColor) async {<br>    ByteData? byteData = await imageToBytes(image);<br>    if (byteData == null) return null;<br><br>    int width = image.width;<br>    int height = image.height;<br>    ui.Color originalColor = getPixelColor(bytes: byteData, x: startX, y: startY, imageWidth: width);<br><br>    _floodFillUtil(byteData, startX, startY, width, height, originalColor, newColor);<br>    <br>    return imageFromBytes(byteData, width, height);<br>  }<br><br>  void _floodFillUtil(ByteData bytes, int x, int y, int width, int height, ui.Color originalColor, ui.Color newColor) {<br>    // Check if current node is inside the boundary and not already filled<br>    if (!_isInside(x, y, width, height) || !isAlmostSameColor(pixelColor: getPixelColor(bytes: bytes, x: x, y: y, imageWidth: width), checkColor: originalColor, imageWidth: width)) return;<br><br>    // Set the node<br>    setPixelColor(x: x, y: y, bytes: bytes, imageWidth: width, newColor: newColor);<br><br>    // Perform flood-fill one step in each direction<br>    _floodFillUtil(bytes, x + 1, y, width, height, originalColor, newColor); // East<br>    _floodFillUtil(bytes, x - 1, y, width, height, originalColor, newColor); // West<br>    _floodFillUtil(bytes, x, y - 1, width, height, originalColor, newColor); // North<br>    _floodFillUtil(bytes, x, y + 1, width, height, originalColor, newColor); // South<br>  }<br><br>  bool _isInside(int x, int y, int width, int height) {<br>    return x &gt;= 0 &amp;&amp; x &lt; width &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; height;<br>  }<br>}</pre><p>Similarly for Queued and Span:</p><pre>import &#39;dart:async&#39;;<br>import &#39;dart:typed_data&#39;;<br>import &#39;dart:ui&#39; as ui;<br>import &#39;dart:collection&#39;;<br><br>class ImageFloodFillQueueImpl extends FloodFill&lt;ui.Image, ui.Color&gt; {<br>  ImageFloodFillQueueImpl(ui.Image image) : super(image);<br><br>  @override<br>  Future&lt;ui.Image?&gt; fill(int startX, int startY, ui.Color newColor) async {<br>    ByteData? byteData = await imageToBytes(image);<br>    if (byteData == null) return null;<br><br>    int width = image.width;<br>    int height = image.height;<br>    ui.Color oldColor = getPixelColor(bytes: byteData, x: startX, y: startY, imageWidth: width);<br><br>    final Queue&lt;Point&gt; queue = Queue();<br>    queue.add(Point(startX, startY));<br><br>    while (queue.isNotEmpty) {<br>      final Point point = queue.removeFirst();<br>      final int x = point.x;<br>      final int y = point.y;<br><br>      if (isAlmostSameColor(pixelColor: getPixelColor(bytes: byteData, x: x, y: y, imageWidth: width), checkColor: oldColor, imageWidth: width)) {<br>        setPixelColor(x: x, y: y, bytes: byteData, imageWidth: width, newColor: newColor);<br><br>        if (x &gt; 0) queue.add(Point(x - 1, y));<br>        if (x &lt; width - 1) queue.add(Point(x + 1, y));<br>        if (y &gt; 0) queue.add(Point(x, y - 1));<br>        if (y &lt; height - 1) queue.add(Point(x, y + 1));<br>      }<br>    }<br><br>    return imageFromBytes(byteData, width, height);<br>  }<br>}<br><br>class Point {<br>  final int x;<br>  final int y;<br><br>  const Point(this.x, this.y);<br>}</pre><pre>import &#39;dart:async&#39;;<br>import &#39;dart:typed_data&#39;;<br>import &#39;dart:ui&#39; as ui;<br><br>class ImageFloodFillSpanImpl extends FloodFill&lt;ui.Image, ui.Color&gt; {<br>  ImageFloodFillSpanImpl(ui.Image image) : super(image);<br><br>  @override<br>  Future&lt;ui.Image?&gt; fill(int startX, int startY, ui.Color newColor) async {<br>    ByteData? byteData = await imageToBytes(image);<br>    if (byteData == null) return null;<br><br>    int width = image.width;<br>    int height = image.height;<br>    ui.Color targetColor = getPixelColor(bytes: byteData, x: startX, y: startY, imageWidth: width);<br><br>    var s = &lt;List&lt;int&gt;&gt;[];<br>    s.add([startX, startX, startY, 1]);<br>    s.add([startX, startX, startY - 1, -1]);<br><br>    while (s.isNotEmpty) {<br>      var tuple = s.removeLast();<br>      var x1 = tuple[0];<br>      var x2 = tuple[1];<br>      var y = tuple[2];<br>      var dy = tuple[3];<br><br>      var nx = x1;<br>      if (_isInside(nx, y, width, height, byteData, targetColor)) {<br>        while (_isInside(nx - 1, y, width, height, byteData, targetColor)) {<br>          setPixelColor(x: nx - 1, y: y, bytes: byteData, imageWidth: width, newColor: newColor);<br>          nx--;<br>        }<br>        if (nx &lt; x1) {<br>          s.add([nx, x1 - 1, y - dy, -dy]);<br>        }<br>      }<br><br>      while (x1 &lt;= x2) {<br>        while (_isInside(x1, y, width, height, byteData, targetColor)) {<br>          setPixelColor(x: x1, y: y, bytes: byteData, imageWidth: width, newColor: newColor);<br>          x1++;<br>        }<br>        if (x1 &gt; nx) {<br>          s.add([nx, x1 - 1, y + dy, dy]);<br>        }<br>        if (x1 - 1 &gt; x2) {<br>          s.add([x2 + 1, x1 - 1, y - dy, -dy]);<br>        }<br>        x1++;<br>        while (x1 &lt; x2 &amp;&amp; !_isInside(x1, y, width, height, byteData, targetColor)) {<br>          x1++;<br>        }<br>        nx = x1;<br>      }<br>    }<br><br>    return imageFromBytes(byteData, width, height);<br>  }<br><br>  bool _isInside(int x, int y, int width, int height, ByteData bytes, ui.Color targetColor) {<br>    if (x &lt; 0 || x &gt;= width || y &lt; 0 || y &gt;= height) return false;<br>    return isAlmostSameColor(pixelColor: getPixelColor(bytes: bytes, x: x, y: y, imageWidth: width), checkColor: targetColor, imageWidth: width);<br>  }<br>}</pre><h4>Checking the result</h4><p>Let’s check the performance of the algorithm. To do this, let’s roll up a screen on which we can try the algorithm in the picture.</p><p><strong>Requirements:</strong></p><ol><li>The picture is downloaded from the internet by url</li><li>When you click on some area, it is painted in red color</li></ol><p>The following code can be used for this:</p><pre>import &#39;dart:typed_data&#39;;<br>import &#39;dart:ui&#39; as ui;<br><br>import &#39;package:flutter/material.dart&#39;;<br><br>import &#39;package:http/http.dart&#39; as http;<br><br>import &#39;flood_fill_raster.dart&#39;;<br><br>class FloodFillRasterScreen extends StatelessWidget {<br>  const FloodFillRasterScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Flood Fill Raster&#39;),<br>      ),<br>      body: const Center(child: FloodFillRaster()),<br>    );<br>  }<br>}<br><br>class FloodFillRaster extends StatefulWidget {<br>  const FloodFillRaster({super.key});<br><br>  @override<br>  State&lt;FloodFillRaster&gt; createState() =&gt; _FloodFillRasterState();<br>}<br><br>class _FloodFillRasterState extends State&lt;FloodFillRaster&gt; {<br>  ui.Image? _image;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _loadImage().then((image) {<br>      setState(() {<br>        _image = image;<br>      });<br>    });<br>  }<br><br>  Future&lt;ui.Image&gt; _loadImage() async {<br>    const url =<br>        &#39;https://sun9-77.userapi.com/impg/BiGYCxYxSuZgeILSzA0dtPcNC7935fdhpW36rg/e3jk6CqTwkw.jpg?size=1372x1372&amp;quality=95&amp;sign=2afb3d42765f8777879e06c314345303&amp;type=album&#39;;<br><br>    final response = await http.get(Uri.parse(url));<br><br>    final Uint8List data = response.bodyBytes;<br>    final ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());<br>    final ui.FrameInfo fi = await codec.getNextFrame();<br>    return fi.image;<br>  }<br><br>  void _onTapDown(TapDownDetails details) async {<br>    final Offset localPosition = details.localPosition;<br>    final int x = localPosition.dx.toInt();<br>    final int y = localPosition.dy.toInt();<br><br>    const ui.Color newColor = Colors.red;<br>    final image = await ImageFloodFillImpl(_image!).fill(x, y, newColor);<br>    setState(() {<br>      _image = image;<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    if (_image == null) {<br>      return const Center(<br>        child: CircularProgressIndicator(),<br>      );<br>    }<br>    return FittedBox(<br>      child: GestureDetector(<br>        onTapDown: _onTapDown,<br>        child: CustomPaint(<br>          size: Size(_image!.width.toDouble(), _image!.height.toDouble()),<br>          painter: ImagePainter(_image!),<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>class ImagePainter extends CustomPainter {<br>  final ui.Image image;<br><br>  const ImagePainter(this.image);<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    canvas.drawImage(image, Offset.zero, Paint()..filterQuality = FilterQuality.high);<br>  }<br><br>  @override<br>  bool shouldRepaint(ImagePainter oldDelegate) =&gt; true;<br>}</pre><p>Explanations:</p><ol><li>The library <a href="https://pub.dev/packages/http">http</a> is used to execute a request to get a picture by url</li><li>The algorithm implementations are in a separate file, so we import the contents as well import &#39;flood_fill_raster.dart&#39;;</li><li>CustomPaint widget is used to draw ui.Image</li><li>GestureDetector is used for handling tapping on the image</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*14lLv-eKLRqRlStx.gif" /></figure><p>This example shows the implementation of ImageFloodFillQueueImpl. Everything is OK with ImageFloodFillSpanImpl as well.</p><p>When using ImageFloodFillImpl, where simple recursion is implemented, errors appear, the nature of which I didn’t bother to look into.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SOcixUdImK7cUmds.png" /><figcaption>Errors using ImageFloodFillImpl</figcaption></figure><p>Thus, we will finally compare the shading speed of both of the remaining working algorithms by clicking on a single point in the image:</p><pre> void _onTapDown(TapDownDetails details) async {<br>    final Offset localPosition = details.localPosition;<br>    final int x = localPosition.dx.toInt();<br>    final int y = localPosition.dy.toInt();<br><br>    const ui.Color newColor = Colors.red;<br><br>    final Stopwatch stopwatchQueue = Stopwatch()..start();<br>    await ImageFloodFillQueueImpl(_image!).fill(x, y, newColor);<br>    stopwatchQueue.stop();<br>    print(&#39;Queue: ${stopwatchQueue.elapsedMilliseconds} ms&#39;);<br>    <br>    final Stopwatch stopwatchSpan = Stopwatch()..start();<br>    await ImageFloodFillSpanImpl(_image!).fill(x, y, newColor);<br>    stopwatchSpan.stop();<br>    print(&#39;Span: ${stopwatchSpan.elapsedMilliseconds} ms&#39;);<br><br>    // setState(() {<br>    //   _image = image;<br>    // });<br>  }</pre><p>And let’s also add a runtime measurement in the floodfill_image library in <a href="https://github.com/garlen-javier/FloodFill_Image/blob/main/lib/src/floodfill_painter.dart#L93">the fill method</a></p><pre>void fill(Offset position) async {<br>    final date_0 = DateTime.now();<br>    int pX = position.dx.toInt();<br>    int pY = position.dy.toInt();<br><br>    if (_filler == null) return;<br><br>    if (pX &lt; 0 || pY &lt; 0) return;<br><br>    int touchColor = _filler!.image!.getPixelSafe(pX, pY);<br>    if (_checkAvoidColor(touchColor)) return;<br>    if (onFloodFillStart != null) onFloodFillStart!(position, image);<br><br>    _filler?.setTargetColor(touchColor);<br>    await _filler!.floodFill(pX, pY);<br><br>    ui.decodeImageFromPixels(<br>      _filler!.image!.getBytes(),<br>      _filler!.image!.width,<br>      _filler!.image!.height,<br>      ui.PixelFormat.rgba8888,<br>      (output) async {<br>        image = output;<br>        final date_1 = DateTime.now();<br>        print(&#39;Flood fill time: ${date_1.difference(date_0).inMilliseconds} ms&#39;);<br>        notifier!.value = position.toString() + touchColor.toString();<br>        if (onFloodFillEnd != null) onFloodFillEnd!(output);<br>      },<br>    );<br>  }</pre><p>And fix the screen:</p><pre>class FloodFillRasterScreen extends StatelessWidget {<br>  const FloodFillRasterScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Flood Fill Raster&#39;),<br>      ),<br>      body: const SingleChildScrollView(<br>          child: Column(<br>        children: [<br>          FloodFillRaster(),<br>          FittedBox(<br>            child: FloodFillImage(<br>              imageProvider: NetworkImage(<br>                  &#39;https://sun9-77.userapi.com/impg/BiGYCxYxSuZgeILSzA0dtPcNC7935fdhpW36rg/e3jk6CqTwkw.jpg?size=1372x1372&amp;quality=95&amp;sign=2afb3d42765f8777879e06c314345303&amp;type=album&#39;),<br>              fillColor: Colors.red,<br>              avoidColor: [Colors.black],<br>              tolerance: 50,<br>            ),<br>          ),<br>        ],<br>      )),<br>    );<br>  }<br>}</pre><h4>The result:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4e7OJon5Te1b3-sV.png" /></figure><p>The first three lines are the time to paint large areas. The lower ones — relatively small areas. Span and library implementation behave approximately the same, Queue — lags behind when painting large areas.</p><h3>Conclusion</h3><p>Today we have looked at how we can implement coloring of bitmap images using flood fill algorithm, used ChatGPT services to write the code, and compared the ready implementation of the algorithm in floodfill_image library with ours.</p><p>I hope this article has given someone else some ideas on how to use ChatGPT in their work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=005702edff1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement image cropping in flutter without third-party libraries]]></title>
            <link>https://medium.com/@RuslanTsitser/how-to-implement-image-cropping-in-flutter-without-third-party-libraries-a0e1597ad435?source=rss-6114125bf8b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0e1597ad435</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Ruslan Tsitser]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 21:39:43 GMT</pubDate>
            <atom:updated>2024-02-17T14:39:44.428Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ut2vz2ze6Lr77McE.png" /></figure><p>Today, we’ll explore how basic mathematics and Flutter’s built-in tools can be used for image editing. We’ll first examine existing libraries offering this functionality, then develop our own solution using GestureDetector, CustomPainter, RepaintBoundary, and GlobalKey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*uB7Z-YnH8F2VotIX.gif" /></figure><h3>Existing Solutions</h3><p>Before presenting my implementation, I’ll briefly discuss some convenient libraries available for image editing. Here are a few notable examples:</p><p><a href="https://pub.dev/packages/image_cropper"><strong>image_cropper</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/0*41-qvSlIZb4yiD2S.gif" /></figure><p>This library uses PlatformChannels for image manipulation, not direct Dart code.</p><p>Challenges with this library include limited customization, platform-specific setup requirements, and lack of desktop support.</p><p>It’s suitable if you’re only seeking functionality with standard user experience, without specific design requirements.</p><p><a href="https://pub.dev/packages/crop_image"><strong>crop_image</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HObtUxmcW7jzZKhp.png" /></figure><p>An image manipulation library that acts as a wrapper of <a href="https://pub.dev/packages/image">Image library</a>, providing standard functionalities for image editing. Unlike the previous one, it supports all platforms without specific settings but has similar UI customization limits. It’s ideal for projects where quick functional addition is crucial without design requirements.</p><p><a href="https://pub.dev/packages/image"><strong>Image</strong></a></p><p>This library offers a wide range of image manipulations without providing ready-made widgets.</p><p>Its advantages include an easy-to-use interface, extensive functionality ranging from simple cropping to pixel-level control, and no UI limitations.</p><p>Potential drawbacks might include being an additional project dependency, naming conflicts (e.g., ‘Image’ class in both dart:ui and package:image/image.dart), and the need for transformations of Image object between libraries as described <a href="https://github.com/brendan-duncan/image/blob/main/doc/flutter.md">here</a>.</p><p>This library is well-suited for projects with specific UI requirements</p><h3>Implementing a Custom Solution</h3><p>After reviewing available solutions, let’s see how Flutter alone, without extra dependencies, can be used for this task.</p><p><strong>Requirements:</strong></p><ol><li>Display an image from a URL.</li><li>Have a transparent rectangle move over the image.</li><li>Allow scaling of the rectangle.</li><li>Save the cropped image upon clicking a save icon.</li></ol><h4>Displaying Image from URL</h4><p>A straightforward method to display images from a specified URL:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class ImageEditorScreen extends StatelessWidget {<br>  const ImageEditorScreen({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Image Editor&#39;),<br>        actions: [<br>          IconButton(<br>            onPressed: () {<br>              // TODO: Save image<br>            },<br>            icon: const Icon(Icons.save),<br>          ),<br>        ],<br>      ),<br>      body: Center(<br>        child: Image.network(&#39;https://picsum.photos/id/418/400/700&#39;),<br>      ),<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7bDMMzUnoWMPfhaK.png" /><figcaption>1 step</figcaption></figure><p>For this, a service for random placeholder images with specified dimensions is used (<a href="https://picsum.photos/">https://picsum.photos</a>).</p><h4>Moving and Scalable Rectangle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*4-GX6q6eYkL0uMbm.gif" /><figcaption>2nd and 3rd steps</figcaption></figure><h4>A Bit of Mathematics</h4><p>To implement a moving rectangle, let’s recall some vector algebra.</p><p>First, about the identity matrix. This is a square matrix in which the elements of the main diagonal are equal to one. The main diagonal is the diagonal from the top left corner to the bottom right corner. It can be represented in the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wLMyIgCprEMboVUpyNa-dA.png" /></figure><p>Here are examples of 2x2, 3x3, 4x4 matrices, respectively. The peculiarity of such matrices is that when another matrix is multiplied by the identity matrix, no changes occur.</p><p>What does it mean to multiply one matrix by another?</p><p>This means to take the first element of the first row of the first matrix and multiply it by the first element of the first column of the second matrix, then add the product of the first row’s second column element of the first matrix and the second row’s first column element of the second matrix, and so on, until we have gone through all the elements of the first row of the first matrix. The result will be the value of the element in the first row, first column of the resulting matrix.</p><p>Then, do the same with the second row of the first matrix. The multiplication with the elements of the first column of the second matrix will give the value of the element in the second row, first column of the resulting matrix. And so on for all the rows of the first matrix.</p><p>After we have gone through all the rows of the first matrix, we move to the second column of the second matrix and start calculating the values for the second column of the resulting matrix anew.</p><p>Or, for clarity, we can represent it in this way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jgn80tMKOKwgrHf8IXPiWg.png" /><figcaption>A and B are matrices of different sizes; C is the result of multiplying matrix A by matrix B, or the resulting matrix.</figcaption></figure><p>Important points from an algebraic perspective:</p><ol><li>Matrix multiplication is not commutative; the product of AxB is not the same as BxA.</li><li>The number of columns in matrix A must match the number of rows in matrix B.</li><li>The resulting matrix will have as many rows as matrix A (the left operand) and as many columns as matrix B (the right operand).</li></ol><p>Linear Transformation and Transformation Matrix</p><p>Regarding linear transformations, these are operations that change vectors (like points or objects in space) in a specific manner. A transformation matrix is a matrix that demonstrates how this change should be performed.</p><p>The transformation matrix in the context of Dart/Flutter</p><pre>Matrix4(<br>  m11, m12, m13, m14,<br>  m21, m22, m23, m24,<br>  m31, m32, m33, m34,<br>  m41, m42, m43, m44<br>)</pre><ol><li><strong>m11, m22, m33</strong>: Scaling coefficients for the X, Y, and Z axes. They dictate how the size of an object changes in each dimension.</li><li><strong>m12, m13, m23, m21, m31, m32:</strong> Used for rotation and shearing. They determine how an object will be rotated or skewed in space. For instance, a rotation around the Z-axis affects m11, m12, m21, and m22.</li><li><strong>m14, m24, m34:</strong> Often used in 3D graphics for perspective transformations. They influence how objects are displaced or distorted in perspective.</li><li><strong>m41, m42, m43</strong>: Translation components for the X, Y, and Z axes. They define how far an object is moved in each dimension.</li><li><strong>m44</strong>: Typically set to 1, used for maintaining matrix uniformity. In the context of homogeneous coordinates, this element helps maintain correct interactions between different types of transformations.</li></ol><p>Translation Matrix (Matrix4 for translation). This matrix represents movement along the x, y, and z axes:</p><pre>Matrix4(<br>  1,  0,  0,  0,<br>  0,  1,  0,  0,<br>  0,  0,  1,  0,<br>  dx, dy, xz, 1<br>)</pre><p>Scaling Matrix (Matrix4 for scaling). This matrix scales objects in space along the x, y, and z axes:</p><pre>Matrix4(<br>  scaleX, 0,      0,      0,<br>  0,      scaleY, 0,      0,<br>  0,      0,      scaleZ, 0,<br>  0,      0,      0,      1<br>)</pre><p>Identity Matrix (Matrix4.identity()): This matrix does not make any changes to the object it is applied to. It’s the basic form of Matrix4:</p><pre>Matrix4(<br>  1, 0, 0, 0,<br>  0, 1, 0, 0,<br>  0, 0, 1, 0,<br>  0, 0, 0, 1<br>)</pre><p><strong>What does this mean for us?</strong></p><p>The red square in the GIF is, roughly speaking, red-colored pixels located at specific coordinates in space. Through linear transformations, we can affect the coordinates of these pixels by scaling, moving, or rotating them.</p><p>There is a Transform widget that takes a transform object of Matrix4, which is a transformation matrix, as an argument. Let’s implement a widget where you can change the transform:</p><pre>class MovingRectWrapper extends StatefulWidget {<br>  const MovingRectWrapper({super.key, required this.child});<br>  final Widget child;<br><br>  @override<br>  State&lt;MovingRectWrapper&gt; createState() =&gt; MovingRectWrapperState();<br>}<br><br>class MovingRectWrapperState extends State&lt;MovingRectWrapper&gt; {<br>  Offset _focalPoint = Offset.zero;<br>  double _scale = 1.0;<br>  Matrix4 _matrix = Matrix4.identity();<br>  final double _width = 100.0;<br>  final double _height = 100.0;  <br>  <br>  void _onScaleStart(ScaleStartDetails details) {<br>    _focalPoint = details.focalPoint;<br>    _scale = 1.0;<br>  }<br><br>  void _onScaleUpdate(ScaleUpdateDetails details) {<br>    Matrix4 matrix = _matrix;<br><br>    // Translation<br>    final newFocalPoint = details.focalPoint;<br>    final offsetDelta = (newFocalPoint - _focalPoint);<br>    _focalPoint = newFocalPoint;<br>    final offsetDeltaMatrix = _getTranslateMatrix(offsetDelta);<br>    matrix = offsetDeltaMatrix * matrix;<br><br>    // Scaling<br>    final newScale = details.scale;<br>    if (newScale != 1.0) {<br>      final scaleDelta = newScale / _scale;<br>      _scale = newScale;<br>      final scaleDeltaMatrix = _getScaleMatrix(scaleDelta);<br>      matrix = scaleDeltaMatrix * matrix;<br>    }<br><br>    setState(() {<br>      _matrix = matrix;<br>    });<br>  }<br><br>  void _onReset() {<br>    setState(() {<br>      _matrix = Matrix4.identity();<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return GestureDetector(<br>      behavior: HitTestBehavior.opaque,<br>      onDoubleTap: _onReset,<br>      onScaleStart: _onScaleStart,<br>      onScaleUpdate: _onScaleUpdate,<br>      child: Stack(<br>        alignment: Alignment.center,<br>        children: [<br>          widget.child,<br>          Transform(<br>            transform: _matrix,<br>            child: SizedBox(<br>              width: _width,<br>              height: _height,<br>              child: DecoratedBox(<br>                decoration: BoxDecoration(<br>                  color: Colors.transparent,<br>                  border: Border.all(<br>                    color: Colors.red,<br>                    width: 2,<br>                  ),<br>                ),<br>              ),<br>            ),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}<br><br>Matrix4 _getTranslateMatrix(Offset offsetDelta) {<br>  final dx = offsetDelta.dx;<br>  final dy = offsetDelta.dy;<br>  return Matrix4(<br>    1, 0, 0, 0, // comments are used for readable formatting<br>    0, 1, 0, 0, // of Matrix4 arguments<br>    0, 0, 1, 0, //<br>    dx, dy, 0, 1, //<br>  );<br>}<br><br>Matrix4 _getScaleMatrix(double scale) {<br>  return Matrix4(<br>    scale, 0, 0, 0, //<br>    0, scale, 0, 0, //<br>    0, 0, 1, 0, //<br>    0, 0, 0, 1, //<br>  );<br>}</pre><ul><li>Matrix4 _matrix: Stores the current transformation value.</li><li>Offset _focalPoint: Coordinates of the touch point on the screen, used for calculating relative displacement.</li><li>double _scale: Stores the current scale, used for scale change calculations.</li><li>Methods _onScaleStart(ScaleStartDetails details) and _onScaleUpdate(ScaleUpdateDetails details) for setting initial values and calculating the transformation matrix.</li><li>_onReset() method for resetting the transform.</li><li>Functions _getTranslateMatrix(Offset offsetDelta) and _getScaleMatrix(double scaleDelta) for returning translation and scaling matrices.</li></ul><p>The moving rectangle is ready, now let’s move on to implementing the final requirement.</p><h4>Obtaining the Cropped Image</h4><p>We have reached the point where we can move the rectangle across the picture. We know its initial dimensions and coordinates, as well as the transformations that have been applied to it. Consequently, we can determine its current center coordinates and dimensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*aZb94dbiKQf7lb5i.gif" /><figcaption>the last requirement</figcaption></figure><p>Let’s add the following getters to the state of the MovingRectWrapper widget:</p><pre>  Size get size =&gt; Size(<br>        _width * _matrix[0],<br>        _height * _matrix[5],<br>      );<br>  Offset get center =&gt; Offset(<br>        _matrix[12] + context.size!.width / 2 - _width / 2 + size.width / 2,<br>        _matrix[13] + context.size!.height / 2 - _height / 2 + size.height / 2,<br>      );</pre><p><strong>Small explanations</strong>:</p><p>To correctly determine the coordinates of the displaced center of the scaled square, for example, for the X-axis:</p><ol><li>Take the offset along the axis _matrix[12]</li><li>Add a correction for half the width of the widget itself context.size!.width / 2, since in the stack all child widgets are by default positioned in the center due to Alignment.center</li><li>Subtract half of the initial width of the square to find the position of its far left point on the X-axis</li><li>Add half of the scaled width to find the current coordinate of the center.</li></ol><p>Similar calculations for the center coordinate on the Y-axis</p><p><strong>Explanations for the matrix arguments</strong>:<br>The 12th element of the matrix is responsible for displacement along the X-axis; 13th — along the Y-axis; the 0th element (upper left on the main diagonal) — this is scaling along the X-axis; The 5th element — it’s a movie that it’s time to rewatch :)</p><p>Taking into account the moving square, we currently have this implementation of the main screen:</p><pre>class ImageEditorScreen extends StatelessWidget {<br>  const ImageEditorScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Image Editor&#39;),<br>        actions: [<br>          IconButton(<br>            onPressed: () {<br>              // TODO: Save image<br>            },<br>            icon: const Icon(Icons.save),<br>          ),<br>        ],<br>      ),<br>      body: Center(<br>        child: MovingRectWrapper(<br>          child: Image.network(&#39;https://picsum.photos/id/418/400/700&#39;),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>The implementation of the second screen is done through CustomPaint:</p><pre>class CroppedImageScreen extends StatelessWidget {<br>  const CroppedImageScreen({<br>    super.key,<br>    required this.image,<br>    required this.center,<br>    required this.size,<br>    required this.widgetSize,<br>  });<br>  final ui.Image image;<br>  final Offset center;<br>  final Size size;<br>  final Size widgetSize;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Cropped Image&#39;),<br>      ),<br>      body: Center(<br>        child: CustomPaint(<br>          size: size,<br>          painter: CroppedImagePainter(<br>            image: image,<br>            center: center,<br>            widgetSize: widgetSize,<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>class CroppedImagePainter extends CustomPainter {<br>  const CroppedImagePainter({<br>    required this.image,<br>    required this.center,<br>    required this.widgetSize,<br>  });<br>  final ui.Image image;<br>  final Offset center;<br>  final Size widgetSize;<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final pixelRatio = image.width / widgetSize.width;<br><br>    final src = Rect.fromCenter(<br>      center: Offset(<br>        center.dx * pixelRatio,<br>        center.dy * pixelRatio,<br>      ),<br>      width: size.width * pixelRatio,<br>      height: size.height * pixelRatio,<br>    );<br><br>    final dst = Rect.fromCenter(<br>      center: Offset(<br>        size.width / 2,<br>        size.height / 2,<br>      ),<br>      width: size.width,<br>      height: size.height,<br>    );<br><br>    canvas.drawImageRect(<br>      image,<br>      src,<br>      dst,<br>      Paint(),<br>    );<br>  }<br><br>  @override<br>  bool shouldRepaint(CroppedImagePainter oldDelegate) =&gt; false;<br>}</pre><p><strong>What’s happening here?</strong></p><p>We pass the ui.Image image to this screen and cut out a rectangle from it, the center of which is located at the coordinates Offset center, and the dimensions of which are Size size. We also pass the dimensions of the widget from which the rectangle is cut out, Size widgetSize. These dimensions are necessary for correctly determining the actual scale sizes of the rectangle in the image.</p><p>A rectangle can be cut from an image using the drawImageRect() method of the Canvas object in the paint() method of CustomPainter. The action of the drawImageRect()method is quite difficult to understand even with a description.</p><p>Here’s how its working principle is described in the documentation:</p><blockquote><em>Draws the subset of the given image described by the </em><em>src argument into the canvas in the axis-aligned rectangle given by the </em><em>dst argument.</em></blockquote><p>After some time, I came to understand how it works and am ready to describe it here.</p><p>Firstly, src, or source, is the part of the image that we want to display. Here, it&#39;s important to specify the real dimensions of the picture, so a correction for pixelRatio is added, which indicates the ratio of the real dimensions of the image to the dimensions occupied on the device&#39;s screen.</p><p>Secondly, dst, or destination, is the rectangle in which we want to draw the cut-out part. Here, you should specify the dimensions that should be on the screen. The coordinates need to be set considering that the top left corner of the rectangle will have coordinates (0;0). It should also be noted that the image will be stretched or compressed if, for example, we cut out a square and decided to place it in a rectangle.</p><p>Examples of how you can, but should not, set dst:</p><p>Here the CustomPaint widget is wrapped in a red Container to give an understanding of the actual size of the widget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q8qgwvi2nWaEhzpx.png" /><figcaption>dst is narrower horizontally</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dyveJU9vccFWtR7c.png" /><figcaption>dst is wider horizontally</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i3CiVBB3B7_qrqu8.png" /><figcaption>dst coordinates are not correctly aligned</figcaption></figure><p>Thus, we approach the main stage — transitioning from the first screen with the moving square to the screen where only the part cut out by the square is displayed. To achieve this, we will use tools available in Flutter — GlobalKey and RepaintBoundary.</p><pre>import &#39;dart:ui&#39; as ui;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter/rendering.dart&#39;;<br><br>final _repaintBoundaryKey = GlobalKey();<br>final _movingRectKey = GlobalKey();<br><br>class ImageEditorScreen extends StatelessWidget {<br>  const ImageEditorScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Image Editor&#39;),<br>        actions: [<br>          IconButton(<br>            onPressed: () {<br>              const double pixelRatio = 3.0;<br>              final RenderRepaintBoundary boundary = _repaintBoundaryKey.currentContext!.findRenderObject() as RenderRepaintBoundary;<br>              final Size widgetSize = boundary.size;<br>              final ui.Image image = boundary.toImageSync(pixelRatio: pixelRatio);<br>              final MovingRectWrapperState state = _movingRectKey.currentState as MovingRectWrapperState;<br>              final Offset rectCenterOffset = state.center;<br>              final Size rectSize = state.size;<br><br>              Navigator.of(context).push(<br>                MaterialPageRoute(<br>                  builder: (context) =&gt; CroppedImageScreen(<br>                    image: image,<br>                    center: rectCenterOffset,<br>                    size: rectSize,<br>                    widgetSize: widgetSize,<br>                  ),<br>                ),<br>              );<br>            },<br>            icon: const Icon(Icons.save),<br>          ),<br>        ],<br>      ),<br>      body: Center(<br>        child: MovingRectWrapper(<br>          key: _movingRectKey,<br>          child: RepaintBoundary(<br>            key: _repaintBoundaryKey,<br>            child: Image.network(&#39;https://picsum.photos/id/418/400/700&#39;),<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Here, we wrapped Image.network in RepaintBoundary and added a GlobalKey. Remember, RepaintBoundary is a widget that creates a separate rendering layer for its child. This widget is often used to improve performance by avoiding the rebuilding of heavyweight widgets during internal or external animations. In our case, we will use its property that allows obtaining a RenderObject with a global key, and from it, the rendered widget in the form of an image.</p><p>Also, by adding a GlobalKey to MovingRectWrapper, we can access its current state, and consequently, the previously mentioned public getters Size get size and Offset get center.</p><p><strong>Final Code</strong>:</p><pre>import &#39;dart:ui&#39; as ui;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter/rendering.dart&#39;;<br><br>final _repaintBoundaryKey = GlobalKey();<br>final _movingRectKey = GlobalKey();<br>class ImageEditorScreen extends StatelessWidget {<br>  const ImageEditorScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Image Editor&#39;),<br>        actions: [<br>          IconButton(<br>            onPressed: () {<br>              const double pixelRatio = 3.0;<br>              final RenderRepaintBoundary boundary =<br>                  _repaintBoundaryKey.currentContext!.findRenderObject() as RenderRepaintBoundary;<br>              final Size widgetSize = boundary.size;<br>              final ui.Image image = boundary.toImageSync(pixelRatio: pixelRatio);<br>              final MovingRectWrapperState state = _movingRectKey.currentState as MovingRectWrapperState;<br>              final Offset rectCenterOffset = state.center;<br>              final Size rectSize = state.size;<br>              Navigator.of(context).push(<br>                MaterialPageRoute(<br>                  builder: (context) =&gt; CroppedImageScreen(<br>                    image: image,<br>                    center: rectCenterOffset,<br>                    size: rectSize,<br>                    widgetSize: widgetSize,<br>                  ),<br>                ),<br>              );<br>            },<br>            icon: const Icon(Icons.save),<br>          ),<br>        ],<br>      ),<br>      body: Center(<br>        child: MovingRectWrapper(<br>          key: _movingRectKey,<br>          child: RepaintBoundary(<br>            key: _repaintBoundaryKey,<br>            child: Image.network(&#39;https://picsum.photos/id/418/400/700&#39;),<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>class MovingRectWrapper extends StatefulWidget {<br>  const MovingRectWrapper({super.key, required this.child});<br>  final Widget child;<br><br>  @override<br>  State&lt;MovingRectWrapper&gt; createState() =&gt; MovingRectWrapperState();<br>}<br><br>class MovingRectWrapperState extends State&lt;MovingRectWrapper&gt; {<br>  Offset _focalPoint = Offset.zero;<br>  double _scale = 1.0;<br>  Matrix4 _matrix = Matrix4.identity();<br>  final double _width = 100.0;<br>  final double _height = 100.0;<br><br>  Offset get center =&gt; Offset(<br>        _matrix[12] + context.size!.width / 2 - _width / 2 + size.width / 2,<br>        _matrix[13] + context.size!.height / 2 - _height / 2 + size.height / 2,<br>      );<br>  Size get size =&gt; Size(<br>        _width * _matrix[0],<br>        _height * _matrix[5],<br>      );<br><br>  void _onReset() {<br>    setState(() {<br>      _matrix = Matrix4.identity();<br>      _scale = 1.0;<br>    });<br>  }<br><br>  void _onScaleStart(ScaleStartDetails details) {<br>    _focalPoint = details.focalPoint;<br>    _scale = 1.0;<br>  }<br><br>  void _onScaleUpdate(ScaleUpdateDetails details) {<br>    Matrix4 matrix = _matrix;<br><br>    final newFocalPoint = details.focalPoint;<br>    final offsetDelta = (newFocalPoint - _focalPoint);<br>    _focalPoint = newFocalPoint;<br>    final offsetDeltaMatrix = _getTranslateMatrix(offsetDelta);<br>    matrix = offsetDeltaMatrix * matrix;<br><br>    final newScale = details.scale;<br>    if (newScale != 1.0) {<br>      final scaleDelta = newScale / _scale;<br>      _scale = newScale;<br>      final scaleDeltaMatrix = _getScaleMatrix(scaleDelta);<br>      matrix = scaleDeltaMatrix * matrix;<br>    }<br><br>    setState(() {<br>      _matrix = matrix;<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return GestureDetector(<br>      behavior: HitTestBehavior.opaque,<br>      onDoubleTap: _onReset,<br>      onScaleStart: _onScaleStart,<br>      onScaleUpdate: _onScaleUpdate,<br>      child: Stack(<br>        alignment: Alignment.center,<br>        children: [<br>          widget.child,<br>          Transform(<br>            transform: _matrix,<br>            child: SizedBox(<br>              width: _width,<br>              height: _height,<br>              child: DecoratedBox(<br>                decoration: BoxDecoration(<br>                  color: Colors.transparent,<br>                  border: Border.all(<br>                    color: Colors.red,<br>                    width: 2,<br>                  ),<br>                ),<br>              ),<br>            ),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}<br><br>Matrix4 _getTranslateMatrix(Offset offsetDelta) {<br>  final dx = offsetDelta.dx;<br>  final dy = offsetDelta.dy;<br>  return Matrix4(<br>    1, 0, 0, 0, // comments are used for readable formatting<br>    0, 1, 0, 0, // of Matrix4 arguments<br>    0, 0, 1, 0, //<br>    dx, dy, 0, 1, //<br>  );<br>}<br><br>Matrix4 _getScaleMatrix(double scale) {<br>  return Matrix4(<br>    scale, 0, 0, 0, //<br>    0, scale, 0, 0, //<br>    0, 0, 1, 0, //<br>    0, 0, 0, 1, //<br>  );<br>}<br><br>class CroppedImageScreen extends StatelessWidget {<br>  const CroppedImageScreen({<br>    super.key,<br>    required this.image,<br>    required this.center,<br>    required this.size,<br>    required this.widgetSize,<br>  });<br>  final ui.Image image;<br>  final Offset center;<br>  final Size size;<br>  final Size widgetSize;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Cropped Image&#39;),<br>      ),<br>      body: Center(<br>        child: CustomPaint(<br>          size: size,<br>          painter: CroppedImagePainter(<br>            image: image,<br>            center: center,<br>            widgetSize: widgetSize,<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>class CroppedImagePainter extends CustomPainter {<br>  const CroppedImagePainter({<br>    required this.image,<br>    required this.center,<br>    required this.widgetSize,<br>  });<br>  final ui.Image image;<br>  final Offset center;<br>  final Size widgetSize;<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final pixelRatio = image.width / widgetSize.width;<br><br>    final src = Rect.fromCenter(<br>      center: Offset(<br>        center.dx * pixelRatio,<br>        center.dy * pixelRatio,<br>      ),<br>      width: size.width * pixelRatio,<br>      height: size.height * pixelRatio,<br>    );<br><br>    final dst = Rect.fromCenter(<br>      center: Offset(<br>        size.width / 2,<br>        size.height / 2,<br>      ),<br>      width: size.width,<br>      height: size.height,<br>    );<br><br>    canvas.drawImageRect(<br>      image,<br>      src,<br>      dst,<br>      Paint(),<br>    );<br>  }<br><br>  @override<br>  bool shouldRepaint(CroppedImagePainter oldDelegate) =&gt; false;<br>}</pre><h3>Conclusions</h3><p>We explored several libraries for image editing. There are actually many more, and you can find a suitable option for your project on <a href="https://pub.dev/">pub.dev</a>.</p><p>This article demonstrates one of the possible scenarios for implementing your own image editor using Flutter’s capabilities, namely through GestureDetector, CustomPainter, RepaintBoundary, and GlobalKey. I hope this article will serve as a starting point or give ideas for other similar cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0e1597ad435" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to improve Flutter Application Performance Using FragmentShader]]></title>
            <link>https://medium.com/@RuslanTsitser/how-to-improve-flutter-application-performance-using-fragmentshader-06b7bd93c44a?source=rss-6114125bf8b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/06b7bd93c44a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[shaders]]></category>
            <dc:creator><![CDATA[Ruslan Tsitser]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 14:08:19 GMT</pubDate>
            <atom:updated>2024-02-17T14:39:25.874Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m a Flutter developer, primarily specializing in development for iOS and Android. I enjoy creating applications for entertainment and education.</p><p>Recently, I was tasked with adding a drawing module. It’s a fairly simple feature where you draw a line by moving your finger across the screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*9rlb0wRM2_csZxcnhTwJIg.gif" /></figure><p>I didn’t spend much time thinking about the implementation, so I took the following steps:</p><ul><li>I created a class that would store the main characteristics of the line (coordinates of points, color, and stroke width).</li></ul><pre>class LineObject {<br>  final List&lt;Offset&gt; points;<br>  final Color color;<br>  final double strokeWidth;<br><br>  const LineObject({<br>    required this.points,<br>    this.color = Colors.red,<br>    this.strokeWidth = 20.0,<br>  });<br>}</pre><ul><li>I implemented FingerPainter for the CustomPaint widget, in which I outlined the logic for drawing lines.</li></ul><pre>class FingerPainter extends CustomPainter {<br>  final List&lt;LineObject&gt; lines;<br>  const FingerPainter({<br>    required this.lines,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    for (int index = 0; index &lt; lines.length; index++) {<br>      final line = lines[index];<br>      final paint = Paint()<br>        ..style = PaintingStyle.stroke<br>        ..color = line.color<br>        ..strokeWidth = line.strokeWidth<br>        ..strokeCap = StrokeCap.round;<br><br>      for (var i = 0; i &lt; line.points.length - 1; i++) {<br>        canvas.drawLine(line.points[i], line.points[i + 1], paint);<br>      }<br>    }<br>  }<br><br>  @override<br>  bool shouldRepaint(FingerPainter oldDelegate) =&gt; true;<br>}</pre><ul><li>Next, I implemented the screen itself with the drawing capability.</li></ul><pre>class FingerPainterScreen extends StatefulWidget {<br>  const FingerPainterScreen({super.key});<br><br>  @override<br>  State&lt;FingerPainterScreen&gt; createState() =&gt; _FingerPainterScreenState();<br>}<br><br>class _FingerPainterScreenState extends State&lt;FingerPainterScreen&gt; {<br>  final List&lt;LineObject&gt; lines = [];<br><br>  void _onClearLines() {<br>    setState(() {<br>      lines.clear();<br>    });<br>  }<br><br>  void _onPanUpdate(DragUpdateDetails details) {<br>    setState(() {<br>      lines.last.points.add(details.localPosition);<br>    });<br>  }<br><br>  void _onPanStart(DragStartDetails details) {<br>    setState(() {<br>      lines.add(LineObject(points: [details.localPosition]));<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: _onClearLines,<br>        child: const Icon(Icons.clear),<br>      ),<br>      body: GestureDetector(<br>        onPanStart: _onPanStart,<br>        onPanUpdate: _onPanUpdate,<br>        child: CustomPaint(<br>          size: MediaQuery.sizeOf(context),<br>          painter: FingerPainter(<br>            lines: lines,<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Overall, this is enough for a start. Then, gradually, you can complicate, customize, and optimize…</p><h3>What are the problems in the current implementation?</h3><p>Let’s conduct a brief code review of my own code.</p><p><strong>Firstly, we draw all the lines at once.</strong> In the paint method, a loop is initiated every time, where each line from the list is drawn in sequence. Let’s correct this, leaving the task to FingerPainter to draw only one specific line:</p><pre>class FingerPainter extends CustomPainter {<br>  final LineObject line;<br>  const FingerPainter({<br>    required this.line,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final paint = Paint()<br>      ..style = PaintingStyle.stroke<br>      ..color = line.color<br>      ..strokeWidth = line.strokeWidth<br>      ..strokeCap = StrokeCap.round;<br><br>    for (var i = 0; i &lt; line.points.length - 1; i++) {<br>      canvas.drawLine(line.points[i], line.points[i + 1], paint);<br>    }<br>  }<br><br>  @override<br>  bool shouldRepaint(FingerPainter oldDelegate) =&gt; true;<br>}</pre><p>Let’s also make corrections on the screen itself:</p><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: _onClearLines,<br>        child: const Icon(Icons.clear),<br>      ),<br>      body: GestureDetector(<br>        behavior: HitTestBehavior.opaque,<br>        onPanStart: _onPanStart,<br>        onPanUpdate: _onPanUpdate,<br>        child: Stack(<br>          children: [<br>            for (int index = 0; index &lt; lines.length; index++)<br>              CustomPaint(<br>                size: MediaQuery.sizeOf(context),<br>                painter: FingerPainter(<br>                  line: lines[index],<br>                ),<br>              ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }</pre><p>Now we have a loop in the Stack widget. In GestureDetector, the property behavior has been changed to HitTestBehavior.opaque. By default, GestureDetector responds to hits on the child, or children in the stack. If there are no children, then new lines will also not be created. <br>Why is it better to have the loop specifically in the stack? I’ll return to this question later.</p><p><strong>Secondly, shouldRepaint is always true.</strong> This parameter tells us when to redraw the widget (i.e., call the paint method). If it’s always true, then, accordingly, with any minor change or, for example, a call to build in the parent, a redraw will occur, and all N lines will be redrawn. Let’s add a condition so that the redraw occurs only when the number of points in the line changes.</p><pre>  @override<br>  bool shouldRepaint(FingerPainter oldDelegate) {<br>    return line.points.length != oldDelegate.line.points.length;<br>  }</pre><p>If we follow the steps as in this article, at this stage our lines will stop being drawn again. This is because the condition always returns false.</p><p>The reason is that the class LineObject is not immutable, and we can change the List&lt;Offset&gt; points property without any qualms. It seems there’s nothing wrong with this until a certain point.</p><p>When we first create an instance of the LineObject class, we create a reference to a section in memory. Always, when we change the points property, we do it in the same object, in the same section of memory.</p><p>Since in the constructor of FingerPainter we pass the reference to the LineObject object, at any point in time when shouldRepaint is called, we refer to the same object. Accordingly, the points property has the same length.</p><p>To avoid such a situation, one can deliberately make the class completely immutable, using, for example, the freezed library. Then, if other developers come along, they will be forced to create a new instance of the class instead of changing the properties of the existing instance.</p><p>In this article, let’s get by with creating a copy of the instance, adding the method copyWith:</p><pre>class LineObject {<br>  final List&lt;Offset&gt; points;<br>  final Color color;<br>  final double strokeWidth;<br><br>  const LineObject({<br>    required this.points,<br>    this.color = Colors.red,<br>    this.strokeWidth = 20.0,<br>  });<br><br>  LineObject copyWith({<br>    List&lt;Offset&gt;? points,<br>    Color? color,<br>    double? strokeWidth,<br>  }) {<br>    return LineObject(<br>      points: points ?? this.points,<br>      color: color ?? this.color,<br>      strokeWidth: strokeWidth ?? this.strokeWidth,<br>    );<br>  }<br>}</pre><p>Let’s adjust the _onPanStart and _onPanUpdate methods:</p><pre>  void _onPanStart(DragStartDetails details) {<br>    setState(() {<br>      lines.add(<br>        LineObject(<br>          points: [details.localPosition],<br>        ),<br>      );<br>    });<br>  }<br><br>  void _onPanUpdate(DragUpdateDetails details) {<br>    setState(() {<br>      lines.last = lines.last.copyWith(<br>        points: [...lines.last.points, details.localPosition],<br>      );<br>    });<br>  }</pre><p>Now, when adding a new point, a new object will be created and replaced in the list of lines.</p><p><strong>Thirdly, the redraw is not isolated</strong>. There is a very useful widget called RepaintBoundary. It allows isolating one widget from others, as if “protecting” from unnecessary redraws both itself, when other widgets change, and other widgets when it is redrawn.</p><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: _onClearLines,<br>        child: const Icon(Icons.clear),<br>      ),<br>      body: GestureDetector(<br>        behavior: HitTestBehavior.opaque,<br>        onPanStart: _onPanStart,<br>        onPanUpdate: _onPanUpdate,<br>        child: Stack(<br>          children: [<br>            for (int index = 0; index &lt; lines.length; index++)<br>              RepaintBoundary(<br>                child: CustomPaint(<br>                  size: MediaQuery.sizeOf(context),<br>                  painter: FingerPainter(<br>                    line: lines[index],<br>                  ),<br>                ),<br>              ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }</pre><p>Thus, the redraw occurs only in the last widget from the list.</p><p>As I mentioned earlier, it’s better to move the loop to Stack because it’s simply convenient, as the example above showed.</p><h3>Where is about the FragmentShader?</h3><p>So, we have optimized the current version of the code as best as we could. But what else might be problematic in this implementation?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*UUFNVtG48mPey1TCHjoUxw.png" /><figcaption>Widget tree</figcaption></figure><p>As you can see, the widget tree linearly grows as the number of lines increases, and in this case, each widget has a corresponding RenderObject, which is at least present in memory and at most rendered on the screen in one of the layers. I won’t go into the details of rendering and rasterization, but I’ll describe it in simple terms.</p><p>Let’s say there’s an erasing feature. Most likely, it’s some line with the background color (in our case, a white line).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*BmmKZSeeFWF1JoehZKJHfg.gif" /><figcaption>Erasing mode</figcaption></figure><pre><br>class FingerPainterScreen extends StatefulWidget {<br>  const FingerPainterScreen({super.key});<br><br>  @override<br>  State&lt;FingerPainterScreen&gt; createState() =&gt; _FingerPainterScreenState();<br>}<br><br>class _FingerPainterScreenState extends State&lt;FingerPainterScreen&gt; {<br>  final List&lt;LineObject&gt; lines = [];<br><br>  void _onClearLines() {<br>    setState(() {<br>      lines.clear();<br>    });<br>  }<br><br>  void _onPanUpdate(DragUpdateDetails details) {<br>    setState(() {<br>      lines.last = lines.last.copyWith(<br>        points: [...lines.last.points, details.localPosition],<br>      );<br>    });<br>  }<br><br>  void _onPanStart(DragStartDetails details) {<br>    setState(() {<br>      lines.add(<br>        LineObject(<br>          color: _currentColor,<br>          points: [details.localPosition],<br>        ),<br>      );<br>    });<br>  }<br><br>  Color get _currentColor =&gt; _eraserModeEnabled ? Theme.of(context).scaffoldBackgroundColor : Colors.red;<br>  bool _eraserModeEnabled = false;<br>  void _onToggleEraser(bool value) {<br>    setState(() {<br>      _eraserModeEnabled = value;<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: _onClearLines,<br>        child: const Icon(Icons.clear),<br>      ),<br>      bottomNavigationBar: SafeArea(<br>        child: ListTile(<br>          title: const Text(&#39;Eraser enabled&#39;),<br>          trailing: Switch(<br>            value: _eraserModeEnabled,<br>            onChanged: _onToggleEraser,<br>          ),<br>        ),<br>      ),<br>      body: GestureDetector(<br>        behavior: HitTestBehavior.opaque,<br>        onPanStart: _onPanStart,<br>        onPanUpdate: _onPanUpdate,<br>        child: Stack(<br>          children: [<br>            for (int index = 0; index &lt; lines.length; index++)<br>              RepaintBoundary(<br>                child: CustomPaint(<br>                  size: MediaQuery.sizeOf(context),<br>                  painter: FingerPainter(<br>                    line: lines[index],<br>                  ),<br>                ),<br>              ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>If we draw a thousand red lines and start erasing them in this way, in the end, we might just get a white screen. But in fact, those will still be the same thousand red lines, obscured by another layer of white. This, obviously, affects performance when there are many such layers.</p><p>I’ll provide specific examples from the existing application where the implementation is the same but with the addition of various types of lines, colors, textures, etc:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*f7MQvPpsrcAvCHzsv90zzw.gif" /><figcaption>Example with a large number of lines</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W3cKu0dfzXayWBKKoWtNLw.png" /><figcaption>Frame rendering speed with a large number of lines</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*-aN0u7X45b0tVeyytM_pSA.gif" /><figcaption>Example with an empty canvas</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Snn3SmzTnZxfJthRFGeDBw.png" /><figcaption>Frame rendering speed with an empty canvas</figcaption></figure><p>To solve the problem of displaying a large number of elements on the screen, the idea came to me not to display a large number of elements on the screen :)</p><p>Essentially, the drawn lines are static elements. So, you can turn them into an image and keep it in the background. When adding a new line, update this image.</p><p>To implement this idea, the RepaintBoundary widget comes to the rescue, this time in conjunction with GlobalKey:</p><pre>import &#39;dart:ui&#39; as ui;<br>import &#39;dart:typed_data&#39;;<br><br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter/rendering.dart&#39;;<br><br>class FingerPainterScreen extends StatefulWidget {<br>  const FingerPainterScreen({super.key});<br><br>  @override<br>  State&lt;FingerPainterScreen&gt; createState() =&gt; _FingerPainterScreenState();<br>}<br><br>class _FingerPainterScreenState extends State&lt;FingerPainterScreen&gt; {<br>  final List&lt;LineObject&gt; lines = [];<br><br>  void _onClearLines() {<br>    setState(() {<br>      lines.clear();<br>      _imageBytes = null;<br>    });<br>  }<br><br>  void _onPanUpdate(DragUpdateDetails details) {<br>    setState(() {<br>      lines.last = lines.last.copyWith(<br>        points: [...lines.last.points, details.localPosition],<br>      );<br>    });<br>  }<br><br>  void _onPanStart(DragStartDetails details) {<br>    setState(() {<br>      lines.add(<br>        LineObject(<br>          color: _currentColor,<br>          points: [details.localPosition],<br>        ),<br>      );<br>    });<br>  }<br><br>  Color get _currentColor =&gt; _eraserModeEnabled ? Theme.of(context).scaffoldBackgroundColor : Colors.red;<br>  bool _eraserModeEnabled = false;<br>  void _onToggleEraser(bool value) {<br>    setState(() {<br>      _eraserModeEnabled = value;<br>    });<br>  }<br><br>  final _repaintKey = GlobalKey();<br>  Uint8List? _imageBytes;<br>  Future&lt;void&gt; _capturePng() async {<br>    final boundary = _repaintKey.currentContext!.findRenderObject() as RenderRepaintBoundary;<br>    final image = boundary.toImageSync(pixelRatio: 1.0);<br>    final byteData = await image.toByteData(format: ui.ImageByteFormat.png);<br>    setState(() {<br>      _imageBytes = byteData!.buffer.asUint8List();<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: _onClearLines,<br>        child: const Icon(Icons.clear),<br>      ),<br>      bottomNavigationBar: SafeArea(<br>        child: ListTile(<br>          title: const Text(&#39;Eraser enabled&#39;),<br>          trailing: Switch(<br>            value: _eraserModeEnabled,<br>            onChanged: _onToggleEraser,<br>          ),<br>        ),<br>      ),<br>      body: GestureDetector(<br>        behavior: HitTestBehavior.opaque,<br>        onPanStart: _onPanStart,<br>        onPanUpdate: _onPanUpdate,<br>        onPanEnd: (_) =&gt; _capturePng(),<br>        child: RepaintBoundary(<br>          key: _repaintKey,<br>          child: Stack(<br>            children: [<br>              // for (int index = 0; index &lt; lines.length; index++)<br>              //   RepaintBoundary(<br>              //     child: CustomPaint(<br>              //       size: MediaQuery.sizeOf(context),<br>              //       painter: FingerPainter(<br>              //         line: lines[index],<br>              //       ),<br>              //     ),<br>              //   ),<br>              if (_imageBytes != null)<br>                Positioned.fill(<br>                  child: Image.memory(<br>                    _imageBytes!,<br>                    fit: BoxFit.cover,<br>                  ),<br>                ),<br>              if (lines.isNotEmpty)<br>                RepaintBoundary(<br>                  child: CustomPaint(<br>                    size: MediaQuery.sizeOf(context),<br>                    painter: FingerPainter(<br>                      line: lines.last,<br>                    ),<br>                  ),<br>                ),<br>            ],<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>We wrapped the Stack widget in RepaintBoundary. Then, using the key, we create an image from the widget. The pixelRatio parameter should be set to 1 because we need a 1:1 size. By the way, in other cases, this parameter can be set to a value greater than 1 to increase the resolution of the resulting image.</p><p>In general, this is enough to ensure that the number of renderObjects does not increase, and the widget tree always looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*s376sKwFWHfAc0XcFUgUmA.png" /></figure><p>We want to maximize performance and reduce the number of operations. How can we do that?</p><p>In the CustomPainter, there is a method for drawing images. Let’s write an implementation for it:</p><pre>class ImagePainter extends CustomPainter {<br>  final ui.Image image;<br>  const ImagePainter({<br>    required this.image,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    canvas.drawImage(image, Offset.zero, Paint());<br>  }<br><br>  @override<br>  bool shouldRepaint(ImagePainter oldDelegate) {<br>    return oldDelegate.image != image;<br>  }<br>}</pre><p>Let’s update the code:</p><pre><br>class FingerPainterScreen extends StatefulWidget {<br>  const FingerPainterScreen({super.key});<br><br>  @override<br>  State&lt;FingerPainterScreen&gt; createState() =&gt; _FingerPainterScreenState();<br>}<br><br>class _FingerPainterScreenState extends State&lt;FingerPainterScreen&gt; {<br>  final List&lt;LineObject&gt; lines = [];<br><br>  void _onClearLines() {<br>    setState(() {<br>      lines.clear();<br>      // _imageBytes = null;<br>      _image = null;<br>    });<br>  }<br><br>  void _onPanUpdate(DragUpdateDetails details) {<br>    setState(() {<br>      lines.last = lines.last.copyWith(<br>        points: [...lines.last.points, details.localPosition],<br>      );<br>    });<br>  }<br><br>  void _onPanStart(DragStartDetails details) {<br>    setState(() {<br>      lines.add(<br>        LineObject(<br>          color: _currentColor,<br>          points: [details.localPosition],<br>        ),<br>      );<br>    });<br>  }<br><br>  Color get _currentColor =&gt; _eraserModeEnabled ? Theme.of(context).scaffoldBackgroundColor : Colors.red;<br>  bool _eraserModeEnabled = false;<br>  void _onToggleEraser(bool value) {<br>    setState(() {<br>      _eraserModeEnabled = value;<br>    });<br>  }<br><br>  final _repaintKey = GlobalKey();<br>  // Uint8List? _imageBytes;<br>  ui.Image? _image;<br>  Future&lt;void&gt; _capturePng() async {<br>    final boundary = _repaintKey.currentContext!.findRenderObject() as RenderRepaintBoundary;<br>    final image = boundary.toImageSync(pixelRatio: 1.0);<br>    // final byteData = await image.toByteData(format: ui.ImageByteFormat.png);<br>    setState(() {<br>      // _imageBytes = byteData!.buffer.asUint8List();<br>      _image = image;<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: _onClearLines,<br>        child: const Icon(Icons.clear),<br>      ),<br>      bottomNavigationBar: SafeArea(<br>        child: ListTile(<br>          title: const Text(&#39;Eraser enabled&#39;),<br>          trailing: Switch(<br>            value: _eraserModeEnabled,<br>            onChanged: _onToggleEraser,<br>          ),<br>        ),<br>      ),<br>      body: GestureDetector(<br>        behavior: HitTestBehavior.opaque,<br>        onPanStart: _onPanStart,<br>        onPanUpdate: _onPanUpdate,<br>        onPanEnd: (_) =&gt; _capturePng(),<br>        child: RepaintBoundary(<br>          key: _repaintKey,<br>          child: Stack(<br>            children: [<br>              // for (int index = 0; index &lt; lines.length; index++)<br>              //   RepaintBoundary(<br>              //     child: CustomPaint(<br>              //       size: MediaQuery.sizeOf(context),<br>              //       painter: FingerPainter(<br>              //         line: lines[index],<br>              //       ),<br>              //     ),<br>              //   ),<br>              if (_image != null)<br>                Positioned.fill(<br>                  child: CustomPaint(<br>                    painter: ImagePainter(<br>                      image: _image!,<br>                    ),<br>                  ),<br>                ),<br>              // if (_imageBytes != null)<br>              //   Positioned.fill(<br>              //     child: Image.memory(<br>              //       _imageBytes!,<br>              //       fit: BoxFit.cover,<br>              //     ),<br>              //   ),<br>              if (lines.isNotEmpty)<br>                RepaintBoundary(<br>                  child: CustomPaint(<br>                    size: MediaQuery.sizeOf(context),<br>                    painter: FingerPainter(<br>                      line: lines.last,<br>                    ),<br>                  ),<br>                ),<br>            ],<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>We can stop at this point because things will get more complex from here.<br>I noticed that the quality of images drawn in CustomPainter can be significantly reduced; they become pixelated. This becomes noticeable when you convert a regular beautiful image, for example, from assets to ui.Image and draw it in the Painter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lrhWvEu7S8yEVPk0v0XlIQ.png" /><figcaption>The difference in image quality (left: CustomPaint, right: original)</figcaption></figure><p>To avoid losing quality, we can use a FragmentShader.</p><p>Let’s create a shader file in the assets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*u-MykAnKCgfQXmViYgj3ng.png" /></figure><p>Add it to pubspec.yaml:</p><pre>flutter:<br>  uses-material-design: true<br><br>  shaders:<br>    - assets/shaders/simple_shader.frag<br><br>  assets:<br>    - assets/images/</pre><p>Write the following code for the shader:</p><pre>#include&lt;flutter/runtime_effect.glsl&gt;<br><br>uniform vec2 uResolution; // The resolution of the screen<br><br>uniform sampler2D uTexture; // The texture<br><br>out vec4 fragColor;<br><br>// A function to perform simple anti-aliasing<br>vec4 applyAntiAliasing(vec2 coord) {<br>    vec2 aaLevel = vec2(1.0) / uResolution; // Adjust as needed, ensuring it&#39;s a vec2<br>    vec4 color = vec4(0.0);<br><br>    // Sample the texture at multiple points around the pixel and average them<br>    for (int x = -1; x &lt;= 1; x++) {<br>        for (int y = -1; y &lt;= 1; y++) {<br>            vec2 sampleCoord = coord + vec2(float(x), float(y)) * aaLevel;<br>            color += texture(uTexture, sampleCoord);<br>        }<br>    }<br><br>    return color / 9.0; // Average of the 9 samples<br>}<br><br>void main() {<br>    vec2 st=FlutterFragCoord().xy  / uResolution;<br><br>    // fragColor = texture(uTexture, st);<br><br>    fragColor = applyAntiAliasing(st);<br>}</pre><p>In simple terms:</p><ul><li>uniform vec2 uResolution is a variable with two parameters, representing the size of the widget with width and height. This parameter needs to be set to use the shader.</li><li>uniform sampler2D uTexture is essentially a ui.Image. This parameter also needs to be passed to use the shader.</li><li>out vec4 fragColor is a variable with four parameters, representing the color of the pixel, and it&#39;s what will be the output.</li><li>vec2 st is the coordinate of that pixel in relative units.</li><li>vec4 applyAntiAliasing(vec2 coord) — for smoothing effect (remove pixelation)</li></ul><p>Update ImagePainter to use the shader:</p><pre>class ImagePainter extends CustomPainter {<br>  final ui.Image image;<br>  final ui.FragmentProgram program;<br>  const ImagePainter({<br>    required this.image,<br>    required this.program,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final paint = Paint()<br>      ..shader = _getShader(size)<br>      ..style = PaintingStyle.fill;<br><br>    final rect = Rect.fromPoints(<br>      const Offset(0, 0),<br>      Offset(size.width, size.height),<br>    );<br>    canvas.drawRect(rect, paint);<br>  }<br><br>  ui.FragmentShader _getShader(Size size) {<br>    final shader = program.fragmentShader();<br><br>    // resolution<br>    shader.setFloat(0, size.width);<br>    shader.setFloat(1, size.height);<br><br>    // texture<br>    shader.setImageSampler(0, image!);<br><br>    return shader;<br>  }<br><br>  @override<br>  bool shouldRepaint(ImagePainter oldDelegate) {<br>    return oldDelegate.image != image;<br>  }<br>}</pre><p>Here, in the _getShader method, we set the necessary parameters mentioned above: the widget&#39;s size and the image.</p><p>Update the final code:</p><pre>import &#39;dart:ui&#39; as ui;<br><br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter/rendering.dart&#39;;<br><br>class FingerPainterScreen extends StatefulWidget {<br>  const FingerPainterScreen({super.key});<br><br>  @override<br>  State&lt;FingerPainterScreen&gt; createState() =&gt; _FingerPainterScreenState();<br>}<br><br>class _FingerPainterScreenState extends State&lt;FingerPainterScreen&gt; {<br>  final List&lt;LineObject&gt; lines = [];<br><br>  void _onClearLines() {<br>    setState(() {<br>      lines.clear();<br>      _image = null;<br>    });<br>  }<br><br>  void _onPanUpdate(DragUpdateDetails details) {<br>    setState(() {<br>      lines.last = lines.last.copyWith(<br>        points: [...lines.last.points, details.localPosition],<br>      );<br>    });<br>  }<br><br>  void _onPanStart(DragStartDetails details) {<br>    setState(() {<br>      lines.add(<br>        LineObject(<br>          color: _currentColor,<br>          points: [details.localPosition],<br>        ),<br>      );<br>    });<br>  }<br><br>  Color get _currentColor =&gt; _eraserModeEnabled ? Theme.of(context).scaffoldBackgroundColor : Colors.red;<br>  bool _eraserModeEnabled = false;<br>  void _onToggleEraser(bool value) {<br>    setState(() {<br>      _eraserModeEnabled = value;<br>    });<br>  }<br><br>  final _repaintKey = GlobalKey();<br>  ui.Image? _image;<br>  void _capturePng() {<br>    final boundary = _repaintKey.currentContext!.findRenderObject() as RenderRepaintBoundary;<br>    final image = boundary.toImageSync(pixelRatio: 1.0);<br>    setState(() {<br>      _image = image;<br>    });<br>  }<br><br>  ui.FragmentProgram? _program;<br>  Future&lt;void&gt; _loadMyShader() async {<br>    final fragmentProgram = await ui.FragmentProgram.fromAsset(&#39;assets/shaders/simple_shader.frag&#39;);<br>    setState(() {<br>      _program = fragmentProgram;<br>    });<br>  }<br><br>  Future&lt;void&gt; _onPanEnd(DragEndDetails details) async {<br>    if (_program == null) {<br>      await _loadMyShader();<br>    }<br>    _capturePng();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: _onClearLines,<br>        child: const Icon(Icons.clear),<br>      ),<br>      bottomNavigationBar: SafeArea(<br>        child: ListTile(<br>          title: const Text(&#39;Eraser enabled&#39;),<br>          trailing: Switch(<br>            value: _eraserModeEnabled,<br>            onChanged: _onToggleEraser,<br>          ),<br>        ),<br>      ),<br>      body: GestureDetector(<br>        behavior: HitTestBehavior.opaque,<br>        onPanStart: _onPanStart,<br>        onPanUpdate: _onPanUpdate,<br>        onPanEnd: _onPanEnd,<br>        child: RepaintBoundary(<br>          key: _repaintKey,<br>          child: Stack(<br>            children: [<br>              if (_image != null &amp;&amp; _program != null)<br>                CustomPaint(<br>                  size: MediaQuery.sizeOf(context),<br>                  painter: ImagePainter(<br>                    image: _image!,<br>                    program: _program!,<br>                  ),<br>                ),<br>              if (lines.isNotEmpty)<br>                RepaintBoundary(<br>                  child: CustomPaint(<br>                    size: MediaQuery.sizeOf(context),<br>                    painter: FingerPainter(<br>                      line: lines.last,<br>                    ),<br>                  ),<br>                ),<br>            ],<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br><br>class FingerPainter extends CustomPainter {<br>  final LineObject line;<br>  const FingerPainter({<br>    required this.line,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final paint = Paint()<br>      ..style = PaintingStyle.stroke<br>      ..color = line.color<br>      ..strokeWidth = line.strokeWidth<br>      ..strokeCap = StrokeCap.round;<br><br>    for (var i = 0; i &lt; line.points.length - 1; i++) {<br>      canvas.drawLine(line.points[i], line.points[i + 1], paint);<br>    }<br>  }<br><br>  @override<br>  bool shouldRepaint(FingerPainter oldDelegate) {<br>    return oldDelegate.line.points.length != line.points.length;<br>  }<br>}<br><br>class LineObject {<br>  final List&lt;Offset&gt; points;<br>  final Color color;<br>  final double strokeWidth;<br><br>  const LineObject({<br>    required this.points,<br>    this.color = Colors.red,<br>    this.strokeWidth = 20.0,<br>  });<br><br>  LineObject copyWith({<br>    List&lt;Offset&gt;? points,<br>    Color? color,<br>    double? strokeWidth,<br>  }) {<br>    return LineObject(<br>      points: points ?? this.points,<br>      color: color ?? this.color,<br>      strokeWidth: strokeWidth ?? this.strokeWidth,<br>    );<br>  }<br>}<br><br>class ImagePainter extends CustomPainter {<br>  final ui.Image image;<br>  final ui.FragmentProgram program;<br>  const ImagePainter({<br>    required this.image,<br>    required this.program,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final paint = Paint()<br>      ..shader = _getShader(size)<br>      ..style = PaintingStyle.fill;<br><br>    final rect = Rect.fromPoints(<br>      const Offset(0, 0),<br>      Offset(size.width, size.height),<br>    );<br>    canvas.drawRect(rect, paint);<br>  }<br><br>  ui.FragmentShader _getShader(Size size) {<br>    final shader = program.fragmentShader();<br><br>    // resolution<br>    shader.setFloat(0, size.width);<br>    shader.setFloat(1, size.height);<br><br>    // texture<br>    shader.setImageSampler(0, image);<br><br>    return shader;<br>  }<br><br>  @override<br>  bool shouldRepaint(ImagePainter oldDelegate) {<br>    return oldDelegate.image != image;<br>  }<br>}</pre><h3>Conclusion:</h3><p>We have achieved optimization by reducing unnecessary rebuilds and converting drawn objects into images. Additionally, we used a FragmentShader to preserve image quality.</p><p>I hope that the material in this article will help you in your projects and inspire you to find non-trivial solutions to complex tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06b7bd93c44a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>