<?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 Sviatoslav on Medium]]></title>
        <description><![CDATA[Stories by Sviatoslav on Medium]]></description>
        <link>https://medium.com/@sviatoslav.kliuchev?source=rss-f571c059e43f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RP_nUfISugu8OXwHJWPMDQ.jpeg</url>
            <title>Stories by Sviatoslav on Medium</title>
            <link>https://medium.com/@sviatoslav.kliuchev?source=rss-f571c059e43f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 04:28:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sviatoslav.kliuchev/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[Swift tips #4: Build Arrays Declaratively with ArrayBuilder]]></title>
            <link>https://medium.com/@sviatoslav.kliuchev/swift-tips-4-build-arrays-declaratively-with-arraybuilder-93d0bb674453?source=rss-f571c059e43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/93d0bb674453</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Sviatoslav]]></dc:creator>
            <pubDate>Mon, 26 Jan 2026 20:20:08 GMT</pubDate>
            <atom:updated>2026-01-26T20:43:20.149Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*diOl_9mDLFptgdjv" /><figcaption>Photo by <a href="https://unsplash.com/@andreiamza2000?utm_source=medium&amp;utm_medium=referral">Amza Andrei</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>. I don’t really know what I’m trying to say with this poster</figcaption></figure><p>Hey! These are Swift Tips — quick, short, and useful insights about Swift. No fillers, no long reads, no BS. Just useful things you may not know. Today we will talk about arrays and how to build them in Swift.</p><p>If you’ve been working with Swift for a while, you know the pain of building arrays in a real-world scenario:</p><pre>var array = [Int]()<br><br>array.append(1)<br>array.append(2)<br><br>if condition {<br>    array.append(3)<br>}<br><br>for i in 4...6 {<br>    array.append(i)<br>}<br><br>print(numbers) // [1, 2, 3, 4, 5, 6, 7, 8]</pre><p>🤮 Looks familiar, right? Every time you want to conditionally add elements, loop over something, or combine arrays, you end up writing <strong>imperative hell</strong>. It gets messy fast.</p><p>But what if I tell you that you actually do this instead:</p><pre>let numbers: [Int] = buildArray {<br>    1<br>    2<br>    if condition {<br>        3<br>    }<br>    for i in 4...6 {<br>        i<br>    }<br>    [7, 8]<br>}<br><br>print(numbers) // [1, 2, 3, 4, 5, 6, 7, 8]</pre><p>Nice, clean, readable, intuitive — like SwiftUI <a href="http://twitter.com/ViewBuilder">@ViewBuilder</a> for arrays! Actually it is! But it’s not built-in. There’s been a discussion about whether this magic should be included in Swift’s standard library… <a href="https://forums.swift.org/t/add-arraybuilder-to-the-standard-library/83811/23">https://forums.swift.org/t/add-arraybuilder-to-the-standard-library/83811/23</a></p><p>However, while Swift core team are waiting for the ‘perfect solution’ you can make your code clean right here, right now. No need to wait! :)</p><h3>Install &amp; Use</h3><p><strong>1️⃣ Add the package via Swift Package Manager</strong></p><p>In your Package.swift:</p><pre>dependencies: [<br>    .package(url: &quot;https://github.com/kliuchev/ArrayBuilder.git&quot;, from: &quot;1.0.0&quot;)<br>]</pre><p>Then add ArrayBuilder as a dependency of your target:</p><pre>.target(<br>    name: &quot;MyApp&quot;,<br>    dependencies: [&quot;ArrayBuilder&quot;]<br>)</pre><p>Or if you use <strong>Xcode</strong>, just add it as a dependency</p><p><strong>2️⃣ Import and start using </strong><strong>buildArray</strong></p><pre>import ArrayBuilder<br><br>let numbers: [Int] = buildArray {<br>    1<br>    2<br>    if true {<br>        3<br>    }<br>}<br><br>print(numbers) // [1, 2, 3]</pre><p><strong>That’s it</strong>, now your codebase is 10× more readable, and your job title just leveled up!</p><p>👏 Don’t hesitate to give this tip 50 claps</p><p>⭐ Give a star on GitHub: <a href="https://github.com/kliuchev/ArrayBuilder">https://github.com/kliuchev/ArrayBuilder</a></p><p><strong><em>Bye!</em></strong></p><p>P.S. For those how want to know how to build your own <strong>ArrayBuilder</strong> or even <strong>YourBestDomainSpecificBuilder</strong></p><ol><li><strong>Here is a source code: </strong><a href="https://github.com/kliuchev/ArrayBuilder/blob/main/Sources/ArrayBuilder/ArrayBuilder.swift">https://github.com/kliuchev/ArrayBuilder/blob/main/Sources/ArrayBuilder/ArrayBuilder.swift</a></li><li><strong>Learn about @resultBuilder here</strong> — <a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/attributes#resultBuilder">https://docs.swift.org/swift-book/documentation/the-swift-programming-language/attributes#resultBuilder</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93d0bb674453" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift tips #3: Flaky unit tests]]></title>
            <link>https://blog.stackademic.com/swift-typs-2-flaky-unit-tests-9a05f6052773?source=rss-f571c059e43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a05f6052773</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Sviatoslav]]></dc:creator>
            <pubDate>Sun, 19 Oct 2025 23:00:29 GMT</pubDate>
            <atom:updated>2025-10-21T05:23:49.197Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KhdJywp_uyTHtyLOdGED7g.png" /></figure><p>If you’re a responsible engineer and don’t want every new PR to break your project, you start looking for solutions. You run checks every time before merging into main. Everything works, only working code in main, life is perfect…</p><p>But then you notice something. Some tests start <strong>failing for no reason</strong>. Locally — fine. On your favorite CI/CD — fail. Rerun — fine again.</p><p>At first, it seams like not a big deal. But your codebase grows, tests take 20–30 minutes to run, and flaky failures keep happening. Soon you’re spending <strong>1–3 hours</strong> just to merge a damn good PR you need to merge today and it’s evening and you have plans. Sound familiar? Don’t worry, here’s how to fix it for most of the cases. And it’s simple.</p><h3>Case #1: Don’t wait — await!</h3><p>Suppose you have a class that does something and returns the result via a completion handler. For example, multiply a number by ten:</p><pre>class Dummy {<br>    <br>    private let value: Int<br><br>    init(value: Int) {<br>        self.value = value<br>    }<br>    <br>    func calculation(completion: @escaping (Int) -&gt; Void) {<br>        DispatchQueue.main.async { [weak self] in<br>            guard let value = self?.value else {<br>                return<br>            }<br>            <br>            completion(value * 10)<br>        }<br>    }<br>}</pre><p>A test for it might look like this:</p><pre>// XCTest version<br>final class DummyTests: XCTestCase {<br>    <br>    var sut: Dummy?<br>    <br>    func testShouldMultiplyByTen() {<br>        let expectedResult = 100<br>        let dummy = Dummy(value: 10)<br>        sut = dummy<br><br>        let expectation = XCTestExpectation(description: #function)<br>        <br>        var actualResult: Int = 0<br>        <br>        dummy.calculation { result in<br>            actualResult = result<br>            expectation.fulfill()<br>        }<br>        <br>        wait(for: [expectation], timeout: 0.1)<br>        <br>        XCTAssertEqual(actualResult, expectedResult)<br>    }<br>}</pre><p>XCTest, the old good friend, seems solid, and everything should work fine. The Dummy doesn’t even have a state to worry about. But this guy will stab you in the back exactly when you least expect it — just like 🔪🥗. And here comes Brutus!</p><pre>wait(for: [expectation], timeout: 0.1) </pre><p>This line makes your test wait until your unit is done, right? Wrong! This line waits for a specific amount of time that you provide in the timeout argument. But how can you guarantee that it’s enough? The code in Dummy is pretty simple and should execute almost instantly, but when your CPU is loaded with other tasks, it can take longer than you expect, and sometimes even this simple operation can time out.</p><h4>Solution — Swift Testing can await saying no numbers</h4><p>Replace you test with the a proper modern one:</p><pre>// Swift Testing version<br><br>import Testing<br>@testable import YourApp<br><br>@Suite<br>struct DummyTests {<br>    <br>    @Test<br>    func shouldMultiplyByTen() async {<br>        let expectedResult = 100<br>        let dummy = Dummy(value: 10)<br>                <br>        let actualResult = await withCheckedContinuation({ continuation in<br>            dummy.calculation { continuation.resume(returning: $0) }<br>        })<br>        <br>        <br>        #expect(actualResult == expectedResult)<br>    }<br>}</pre><p>Here, we replaced wait(timeout:) with withCheckedContinuation, which allows us to await the result.</p><p>Now the test is bulletproof. Although your test still has a timeout (and even await has its own), the values are much larger than you might expect. If your test times out in this case, something is wrong with your CI/CD setup, and you probably need to allocate more compute resources ( Bitrise, if you’re reading this, pay up my referral share! 😎💰 ).</p><h3>Case #2: Snapshot tests</h3><p>If you use the swift-snapshot-tests package, you’ve probably already started thinking, &#39;I can do the same thing with my snapshot test, easy!&#39; — but you can’t. The nature of snapshot testing doesn’t allow us to &#39;await the result,&#39; so a simple await won’t help anymore.</p><p>In this case, we need to run snapshot tests separately and one by one to make sure that nothing else is happening on the machine while we are testing snapshots. Here’s how you can do that:</p><h4>Step 1: Create a snapshot tag</h4><p>In case you’re still using XCTest for snapshot testing, stop it right now. Take a bit of time to rewrite the whole thing — it’s not that difficult, and it’s worth the effort.</p><p>For those who already use Swift Testing, your test should look like this:</p><pre>import Testing<br>import SnapshotTesting<br><br>@testable import YourApp<br><br>extension Tag {<br>  @Tag static var snapshots: Self<br>}<br><br>@MainActor<br>@Suite(.serialized, .tags(.snapshots))<br>struct ContentViewTests {<br>    <br>    @Test<br>    func contentView() {<br>        let view = ContentView()<br>        <br>        assertSnapshot(of: view, as: .image)<br>    }<br>}</pre><p>Here are two important things:</p><ol><li>snapshots tag – it will help us run these tests separately from all other tests.</li><li>.serialized – it forces Xcode to run tests in serial.</li></ol><p>Now, when you run tests in Xcode, instead of running all of them, tap the snapshots tag in the sidebar, and your tests will run smoothly.</p><h4>Step 2: Update your CI/CD commands</h4><p>If you use xcodebuild to run your tests, you should create a separate test plan for it — let’s call it SnapshotsTestPlan. Simply create a test plan from the templates in Xcode, choose the target (it should be the unit tests in your project), select Swift Testing, and choose the snapshots tag that we created in the previous step.</p><p>You should see something like this when you click on SnapshotsTestPlan:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ldBGHkWqtwGL-lKKhHy_fg.png" /></figure><p>And don’t forget to add this test plan to your app’s scheme:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WMJFX61DwERkDQgZXMw3xA.png" /></figure><p>Then, when you run your xcodebuild test command, you need to add some additional parameters:</p><ol><li>-disable-concurrent-destination-testing — Makes xcodebuild run snapshot tests in serial.</li><li>-testPlan “SnapshotsTestPlan” — Runs the test plan we created.</li></ol><p>Test your setup by running this command in the terminal:</p><pre>xcodebuild test \<br>  -scheme &quot;YourApp&quot; \<br>  -testPlan &quot;SnapshotsTestPlan&quot; \<br>  -disable-concurrent-destination-testing \<br>  -destination &#39;platform=iOS Simulator,name=iPhone 17&#39;</pre><p><em>*Don’t forget to replace </em><em>YourApp with the name of your scheme and the destination if you use a different one for snapshot tests</em></p><h4>Step 3: Exclude snapshots from your main test plan</h4><p>Don’t forget to exclude the snapshots tag from your main test plan, or you’ll end up running snapshot tests twice — twice as long and with a higher chance of flaky tests. Nobody wants that, do they? To do so, open your main test plan and add snapshots tag to “exclude tags” field.</p><h3>Case 3: Bad tests</h3><p>Sometimes it has nothing to do with flaky tests; sometimes you just created a test incorrectly. Here are some recommendations on how to avoid unexpected test behavior:</p><ol><li><strong>Don’t use shared dependencies</strong> — if your unit dependency is a singleton, a filesystem, or anything mutable, mock it. Sometimes in tests you end up trying to modify the same resource, which can corrupt your input. Mock everything you can to avoid using mutable, shareable dependencies. Remember: <strong>crap in, crap out</strong>. <em>You don’t need to do this with immutable ones, though..</em></li><li><strong>Don’t write logic in your tests</strong> — the moment you start writing extensive logic in a test, you need to split it into simpler ones. In the same way you make mistakes in your units, you can make mistakes in your tests. The simpler the test, the more stable it is.</li><li><strong>Don’t test against the backend development stage</strong> — if your unit test involves communication with your backend API, ask your backend teammates to prepare a stable environment. It’s a pretty common situation when engineers test against an unstable development environment, and even if you agreed that interfaces are stable, if the environment is reloading, your tests will fail. Encourage your team to invest a small amount of time to prevent major issues. If you can’t do that, test against mocks or a dummy server.</li></ol><h3>Conclusions</h3><p>It’s not the full set of methods that can help you avoid flaky tests. You should also consider implementing retry logic in your CI/CD pipeline, disabling external resources (such as WebViews, AsyncImages, etc.) for your snapshot tests, and many other techniques you can use to achieve reliable results. But these recommendations alone will save you a lot of time. If you found this valuable, don’t hesitate to give some claps (50 should be enough 😎👏)</p><p>Cheers!</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a05f6052773" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/swift-typs-2-flaky-unit-tests-9a05f6052773">Swift tips #3: Flaky unit tests</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift tips #2: Make your folder cool!]]></title>
            <link>https://medium.com/@sviatoslav.kliuchev/swift-tips-2-make-your-folder-cool-7608347f7748?source=rss-f571c059e43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7608347f7748</guid>
            <category><![CDATA[beauty]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mac]]></category>
            <dc:creator><![CDATA[Sviatoslav]]></dc:creator>
            <pubDate>Sun, 19 Oct 2025 20:01:33 GMT</pubDate>
            <atom:updated>2025-10-19T20:01:33.604Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L3ws4RzUPmv8r8Kgb7QAmg.png" /></figure><p>Do you know that the directory where you store a local copy of your project doesn’t have to be boring?</p><p>To make it look like in the picture, just do these two simple things:</p><ol><li>Create a directory in your home folder on Mac</li><li>Name it Developer</li></ol><p><strong>Bonus</strong> — put it to the Finder’s sidebar</p><p>And you’ll have this beauty!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5Mkr7uznQeVQU_-_2Q2mg.png" /></figure><p>Now all your projects have ten times more chances to succeed!</p><p>Cheers</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7608347f7748" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift tips #1 — Scripting with Swift]]></title>
            <link>https://medium.com/@sviatoslav.kliuchev/swift-tips-1-scripting-with-swift-9d879a4b2302?source=rss-f571c059e43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d879a4b2302</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[scripting]]></category>
            <dc:creator><![CDATA[Sviatoslav]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 23:22:11 GMT</pubDate>
            <atom:updated>2025-10-19T23:06:50.600Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift tips #1: Scripting with Swift</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sd3DU_AgpGM1-jjlMCkxjA.png" /><figcaption>Like sh but better!</figcaption></figure><p>Every engineer has this moment in their lives when they start thinking — “I should create tooling for my project to make things quicker”. They usually start with bash then feel “it’s not enough — I should use a proper scripting language”. And there are plenty of them: Python, Ruby, JavaScript but why not use swift instead?</p><p>You might say: “Wait a second — I don’t want to compile my code and maintain a binary!” And it’s a legit take — no one wants to go through “write -&gt; run -&gt; build -&gt; put somewhere to execute -&gt; repeat” every time when they just want to do something real quick. I literally feel like I’m getting older doing this. Here is a simple trick that makes your swift files runnable</p><h4>Step 1: Create a script</h4><p>Create a script file: <strong>your_script_name.swift </strong>with some code</p><pre>print(&quot;I&#39;m doing something&quot;)</pre><h4>Step 2: Add shebang</h4><p>Add shebang to the start of the file:</p><pre>#!/usr/bin/env swift<br>print(&quot;I&#39;m doing something&quot;)</pre><h4>Step 3: Give it rights</h4><p>To execute it in your favorite shell, make it executable:</p><pre>chmod +x ./your_script_name.swift</pre><h4>Step 4: Enjoy</h4><p>Now you can run your script the same way that you run any other scripts in <strong>Terminal</strong></p><pre>./your_script_name.swift<br>I&#39;m doing something</pre><p>That’s it, that simple, you don’t need any other programming languages in your code base and strange binaries that you always forget to update. The simple things need simple solutions, spend your saved time for something beautiful.</p><p>Happy scripting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d879a4b2302" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter is a Bad Choice for You (Unless It’s Not)]]></title>
            <link>https://medium.com/@sviatoslav.kliuchev/flutter-is-a-bad-choice-for-you-unless-its-not-a3f082897d3b?source=rss-f571c059e43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3f082897d3b</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Sviatoslav]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 13:15:41 GMT</pubDate>
            <atom:updated>2025-04-10T13:16:16.088Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b3Kzq3MMdWFdjggc" /><figcaption>Photo by <a href="https://unsplash.com/@_k8_?utm_source=medium&amp;utm_medium=referral">K8</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a> Is it related to the article? I don’t think so, but do you even read articles without a poster image? :)</figcaption></figure><p>Today I read an article that mentioned some significant issues with Flutter, and I believe these problems will be around for a long time. If you’re not familiar with the issues, I recommend reading:</p><p><a href="https://medium.com/@lucydev8/flutter-apps-look-cheap-and-untrustworthy-23a36b2755fd"><strong>Flutter issues make apps look cheap and untrustworthy.</strong></a></p><p>You might be wondering:</p><blockquote><em>Should I use Flutter at all if it has so many issues that make my app look off?</em></blockquote><p>Let’s discuss that!</p><h3>What Really Matters?</h3><p>What do you think makes apps great? Beautiful design? Exceptional user experience? The value the app brings to users? The cost of building? All these things matter, but their importance can change depending on the situation. Your priorities can lead your app to success or failure.</p><h3>User interface</h3><p>Everyone — especially developers — wants their app to look and feel great. Users expect polished experiences, and design plays a big role in that. But here’s the truth: <strong>you can’t create a truly native-feeling UI with Flutter.</strong></p><p>Flutter is great for building beautiful UIs with custom designs, but UI isn’t just about looks. It’s also about what users are used to: platform-specific behaviors, gestures, animations, and small details that feel “off” when they’re not native. For example, iOS users instantly notice when something feels unfamiliar, even if they can’t explain why.</p><p>Even if you try to use Cupertino widgets, it still won’t feel 100% native. Animations, text rendering, and interactions are just slightly different. And since your app lives inside the larger iOS system UI, these differences are noticeable.</p><p>You might hear things like “great apps have their own design language,” and that’s true. But native-feeling motion, text, and gestures are still key to a seamless experience. And that’s where Flutter falls short.</p><p>One of the most mentioned examples of a “great UI built with Flutter” is <a href="https://flutter.gskinner.com/"><strong>Wonderous</strong></a><strong>.</strong> To be fair, it looks great. I really like what the engineers achieved there. But let’s be honest — it doesn’t feel native at all. Would you want your Phone, Messages, or Calendar apps to look that different from the rest of iOS? Probably not.</p><p>So, yes, UI is important — but it’s just one piece of the puzzle. There are other things that matter just as much, if not more.</p><h4>Product Experience</h4><p>One of the most critical aspects of a successful app is the <strong>product experience</strong> — how users feel when they interact with your app. This includes not only how it looks, but how intuitive, smooth, and satisfying the overall flow is. A great product experience can turn casual users into loyal ones, while a poor experience can cause them to leave after the first use.</p><p>When designing an app, it’s essential to think beyond visual design and focus on the overall journey: how quickly users can achieve their goals, how consistent and logical the interface is, and whether the app adapts well to different usage scenarios.</p><p>While using Flutter, you may face some limitations in product experience, such as the previously mentioned less-than-perfect UI compared to native platforms. However, aside from that, Flutter gives you almost complete freedom to craft the experience you want. In short, choosing Flutter won’t significantly limit your app’s product experience</p><h4>The Value Your App Brings</h4><p>Another key factor in your app’s success is the value it provides to users. No matter how beautiful the interface is or how smooth the product experience feels — if the app doesn’t solve a real problem or provide meaningful benefits, users won’t stick around.</p><p>Value can come in many forms: saving time, helping users learn something new, simplifying daily tasks, providing entertainment, or offering a better way to do something they already do. The more clearly your app delivers that value, the more likely it is to succeed.</p><p>It’s important to understand that the core value of your app is independent of the UI framework you choose. Whether you’re building with Flutter, SwiftUI, Jetpack Compose, or any other tool, the technology behind the app doesn’t define its value. What matters is the problem you solve and how effectively you solve it.</p><h4>Cost of Building and Time to Market</h4><p>When building an app, <strong>cost</strong> and <strong>time to market</strong> are critical. No matter how great your product is, if you can’t release it quickly. Think of it like building a car — if it takes you years to finish, by the time it’s ready, everyone will have moved on to something else. Similarly, if you spend too much time or money developing, you might run out of resources before you even get to launch.</p><p>Flutter excels in this area by providing a suite of tools designed to speed up development and reduce time to market. <strong>Hot reload</strong>, for instance, allows you to see changes instantly without rebuilding the entire app, saving both time and frustration. On top of that, Flutter has powerful integrations like <strong>Shorebird</strong> and <strong>Serverpod</strong>, which streamline backend integration and make it easier to fix bugs quickly without waiting for approvals in app stores.</p><p>With these tools, you can focus on building features, iterate faster, and get your app in front of users sooner — all while keeping costs as low as possible.</p><h3>When NOT to Use Flutter</h3><p>If you need an app without compromises, without “junk” or “off feelings,” and you have enough resources to maintain two separate applications for both platforms, go native. There’s no reason to choose Flutter in this situation. The only thing you’ll gain is regret, as you’ll never achieve your goals (native look, uncompromised performance, etc.).</p><p>Also, if your app is only for iOS, there’s no reason to use Flutter. Just go with Swift/SwiftUI/UIKit. These will satisfy all your needs without any additional hassle. Whether you’re a solo developer, part of a small team, or a large corporation, it’s about meeting expectations.</p><h3>When to Use Flutter</h3><p>In the real world, especially when resources are limited, time to market is one of the most valuable assets. The faster you can launch your app, the sooner you can test your idea and gather feedback from real users. This helps you avoid wasting time on a project that might not be viable. Flutter’s ability to rapidly develop and iterate is crucial in these situations.</p><h4>Coffee shops, gyms, stores</h4><p>One of the most overlooked use cases for Flutter is in small and mid-sized businesses, where the app is not the central product but simply a tool to enhance the business. Examples include apps for coffee shops, gyms, or retail stores. These apps usually serve a straightforward purpose — collecting loyalty points, providing simple membership features, or displaying essential information like opening hours or promotions.</p><p>In these cases, there’s no need for the app to feel native. The priority is not perfect animations or platform-specific UI behaviors. What matters is that users can easily interact with the app to receive basic benefits. Businesses don’t want to spend extra resources on a sophisticated app when a simple, functional one will do the job.</p><p>Flutter is ideal for such cases because it allows you to build a functional and cost-effective app quickly, without the need for complex UI adjustments.</p><h4>Pet projects</h4><p>Flutter is also a great choice for personal or small-scale projects. If you’re building something for a small group — like an app for your tennis club to track scores or a simple app for your speaking club — Flutter is perfect. It doesn’t require a deep focus on platform-specific features, and you can quickly develop a working prototype that serves the purpose. These apps might not require advanced UI or complex interactions, so Flutter gives you everything you need to build and deploy your project.</p><h4>Minimal Value Product ( MVP )</h4><p>When you’re developing a startup or testing a new idea, speed is critical. The MVP phase is all about getting your app to market quickly to validate your concept. Flutter is particularly strong in this area because it allows you to develop fast without sacrificing too much on functionality. Even if you plan to rewrite the app in native code later, Flutter can help you get your idea off the ground quickly, test it with users, and pivot if necessary.</p><h3>Flutter is not perfect</h3><p>Like many things in life, Flutter is not perfect. While it allows for fast development, there will be limitations, especially if you prioritize a truly native feel. Your app might have quirks or “off” elements, and when you need platform-specific features (like custom widgets or native APIs), you’ll have to rely on native tools.</p><p>Don’t be fooled into thinking Flutter can handle everything. Once you need deeper platform integration, you’ll need to tap into native development. That said, Flutter still makes it easier and faster to bring ideas to life, offering a more cost-effective approach compared to traditional methods. If quick development and validation are what you need, give it a try.</p><p>P.S. What about the competitors? React Native and Jetpack Compose share similar issues with Flutter. React Native is a great choice if you’re already familiar with JavaScript. As for Jetpack Compose, it’s still in development, and despite its advantages, it’s not always production-ready, and even when it will, it will have the same issues.</p><p>P.P.S. Here is a list of apps that will make you understand what is a problem with UI in Flutter not just words:</p><ol><li><a href="https://apps.apple.com/us/app/sncf-connect-trains-routes/id343889987"><strong>SNCF Connect</strong></a><strong> </strong>— Sheets have safe area issues (could be fixed in no time, not a particular Flutter problem, but in native you don’t have things like this by default). A good example of an app that doesn’t require exactly native feelings but still does the job.</li><li><a href="https://apps.apple.com/us/app/reflectly-journal-ai-diary/id1241229134"><strong>Reflectly</strong></a> — Here you can see what is “a little bit off” in terms of the overall great design.</li><li><a href="https://flutter.gskinner.com/wonderous/"><strong>Wonderous</strong></a><strong> </strong>— The app that is way easier to build with Flutter than in SwiftUI/UIKit.</li><li><a href="https://github.com/fluttergems/awesome-open-source-flutter-apps?tab=readme-ov-file"><strong>Flutter open source apps list</strong></a><strong> </strong>— These aren’t production apps, so don’t expect a polished design, but here you can get a glimpse of typical Flutter UI ( with no design of course ) and how it differs from what you get for free with SwiftUI.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3f082897d3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improve AsyncImage in SwiftUI]]></title>
            <link>https://medium.com/@sviatoslav.kliuchev/improve-asyncimage-in-swiftui-5aae28f1a331?source=rss-f571c059e43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aae28f1a331</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[asyncimage]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sviatoslav]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 12:22:03 GMT</pubDate>
            <atom:updated>2025-04-09T19:48:59.651Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimizing AsyncImage in SwiftUI: Build a Custom Cached Solution</h3><figure><img alt="Cool image to catch your attention :)" src="https://cdn-images-1.medium.com/max/1024/0*zlW1sC0UKvRcn-Xl" /><figcaption>Photo by <a href="https://unsplash.com/@viktortalashuk?utm_source=medium&amp;utm_medium=referral">Viktor Talashuk</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a> *Just a cool image to catch your attention :)</figcaption></figure><p>Hi! Apple has given us a great AsyncImage, and it works well in most cases. But today, I’ll show you how to make it <strong>even better</strong>.</p><h3>The problem</h3><p>As you may know, AsyncImage loads an image every time it appears. But what if we need to show the <strong>same image multiple times</strong> on screen at once Do we really need to make <strong>multiple network requests</strong> for the same image? I don’t think so.</p><p>Instead, I’d like a solution that loads the image <strong>only once</strong>, no matter how many views request it. But how can we achieve that?</p><h3>Solution</h3><p>To get this behavior, we’ll build our own version of AsyncImage:</p><pre>struct AsyncImage&lt;Content: View&gt;: View {<br>    @State var model: ViewModel<br>    <br>    private let content: (AsyncImagePhase) -&gt; Content<br>    <br>    init(url: URL, @ViewBuilder content: @escaping (AsyncImagePhase) -&gt; Content) {<br>        self.content = content<br>        self.model = ViewModel(url: url)<br>    }<br>    <br>    var body: some View {<br>        content(model.phase)<br>            .onAppear(perform: model.load)<br>    }<br>    <br>    @Observable<br>    final class ViewModel {<br>        var phase: AsyncImagePhase = .empty<br>        <br>        private let loader: ImageLoader<br>        private var url: URL<br>        private var cancelable: AnyCancellable?<br>        <br>        init(url: URL, loader: ImageLoader = ImageLoaderImpl.shared) {<br>            self.url = url<br>            self.loader = loader<br>        }<br>        <br>        func load() {<br>            cancelable = loader.load(url: url)<br>                .receive(on: DispatchQueue.main)<br>                .sink(receiveValue: { [weak self] phase in<br>                    self?.phase = phase<br>                })<br>        }<br>    }<br>}<br><br>protocol ImageLoader {<br>    func load(url: URL) -&gt; AnyPublisher&lt;AsyncImagePhase, Never&gt;<br>}</pre><p>This custom AsyncImage view uses a ViewModel that calls the load method from an ImageLoader service. I chose to reuse the existing AsyncImagePhase because it fits our needs perfectly. You will find AsyncView without ViewModel at the end of this article.</p><p>Let’s create a basic loader:</p><pre>class ImageLoaderImpl: ImageLoader {<br>    enum Error: Swift.Error {<br>        case imageDecodingFailed<br>    }<br>    <br>    func load(url: URL) -&gt; AnyPublisher&lt;AsyncImagePhase, Never&gt; {<br>        URLSession.shared<br>            .dataTaskPublisher(for: url)<br>            .map({ (data, _) in<br>                if let image = UIImage(data: data) {<br>                    return AsyncImagePhase.success(Image(uiImage: image))<br>                } else {<br>                    return .failure(Error.imageDecodingFailed)<br>                }<br>            })<br>            .catch { Just&lt;AsyncImagePhase&gt;(AsyncImagePhase.failure($0)) }<br>            .eraseToAnyPublisher()<br>    }<br>}</pre><p>In this example, we use a dataTaskPublisher to fetch image data and convert it into an AsyncImagePhase, which we then feed into the view.</p><p>So far, so good — but there’s a problem: <strong>Each instance of </strong><strong>AsyncImage still triggers its own network request. </strong>To solve this, we need to <strong>share</strong> the same publisher for each URL.</p><p>In other words, we’ll cache active requests and return the same publisher if it’s already in progress.</p><p>Here’s how we can do that:</p><pre>class ImageLoaderImpl: ImageLoader {<br>    enum Error: Swift.Error {<br>        case imageDecodingFailed<br>    }<br>    <br>    // Shared instance to provide a common cache for all views.<br>    // Since all views operate on the main thread, we don&#39;t have to worry about data races.<br>    static var shared = ImageLoaderImpl()<br>    <br>    // This dictionary stores the current publisher for a given URL,<br>    // along with a cancellable that removes the publisher from the dictionary<br>    // once the request completes.<br>    var loaders: [URL: (publisher: AnyPublisher&lt;AsyncImagePhase, Never&gt;, cancelable: AnyCancellable)] = [:]<br>    <br>    func load(url: URL) -&gt; AnyPublisher&lt;AsyncImagePhase, Never&gt; {<br>        // If a publisher already exists for this URL, return it.<br>        if let (publisher, _) = loaders[url] {<br>            return publisher<br>        } else {<br>            // Otherwise, create a new one.<br><br>            // This subject will emit AsyncImagePhase values to the AsyncImage.<br>            let subject = CurrentValueSubject&lt;AsyncImagePhase, Never&gt;(.empty)<br><br>            // Erase the subject to AnyPublisher to hide the implementation details from subscribers.<br>            let publisher = subject.eraseToAnyPublisher()<br>            <br>            // Make the request via URLSession.dataTaskPublisher<br>            let cancelable = URLSession<br>                .shared.dataTaskPublisher(for: url)<br>                // Map the response to AsyncImagePhase<br>                .map({ (data, _) in<br>                    if let image = UIImage(data: data) {<br>                        return AsyncImagePhase.success(Image(uiImage: image))<br>                    } else {<br>                        return .failure(Error.imageDecodingFailed)<br>                    }<br>                })<br>                // Convert all errors into AsyncImagePhase<br>                .catch { Just&lt;AsyncImagePhase&gt;(AsyncImagePhase.failure($0)) }<br>                // Send all events to our shared subject<br>                .handleEvents(receiveOutput: subject.send)<br>                // Once we receive the final result, remove the publisher from the dictionary<br>                // and cancel the associated subscription<br>                .sink(receiveValue: { [weak self] _ in<br>                    self?.loaders[url]?.cancelable.cancel()<br>                    self?.loaders[url] = nil<br>                })<br>            <br>            // Store the publisher and subscription in the dictionary<br>            loaders[url] = (publisher: publisher, cancelable: cancelable)<br>            return publisher<br>        }<br>    }<br>}</pre><p>Let’s break it down:</p><ol><li>We added a shared loaders dictionary that stores publishers and their corresponding cancelables.</li><li>If a request is already in progress for a given URL, we return the same publisher.</li><li>Once the request completes, we remove it from the cache.</li></ol><p>This way, multiple views share the same ongoing request — no redundant calls, <strong>no wasted bandwidth.</strong></p><p>Exactly what we wanted!</p><h3>Final Thoughts</h3><p>Today you learn how to:</p><ol><li>Build your own AsyncImage.</li><li>Convert one publisher into another.</li><li>Optimize repeated server requests using Combine.</li></ol><p>This principle isn’t limited to images — you can apply it to <strong>any repeatable request</strong> that benefits from caching.</p><p>Even if you’re not convinced it’s necessary, your backend teammates will definitely thank you. 😉</p><p>Cheers! 🍻</p><h4>Update #1: The cache solution with no cache. How does it works?</h4><p>Thanks <a href="https://medium.com/u/ba1bf5213360">Michael Long</a>, I noticed that the response cache in this solution isn’t explained clearly enough. Since we’re using URLSession in this case, we already have a built-in caching solution. By default, URLSession follows HTTP cache-related headers to decide when it should or shouldn’t download the response body. It works out of the box — no need to add anything on top of that.</p><p>However, if you want to force URLSession to use the cache instead of even making a request (if there is something in the cache, of course), you can configure your own URLSession instance with the cache policy .returnCacheDataDontLoad.</p><p>Here’s how you can do that in this case:</p><pre>final class ImageLoaderImpl: ImageLoader {<br>    ...<br>    private let urlSession: URLSession<br>    init() {<br>        let configuration = URLSessionConfiguration.default<br>        configuration.requestCachePolicy = .returnCacheDataDontLoad<br>        self.urlSession = URLSession(configuration: configuration)<br>    }<br>    ...</pre><p>And now, it uses the cache whenever possible instead of making requests — ignoring cache related headers. You can also set up a custom URLCache for this URLSession if you want. However, I’d recommend sticking with URLSession.shared in this case to keep the behavior predictable.</p><h4>Update #2: We don’t need MVVM in the AsyncView</h4><p>Thanks <a href="https://medium.com/u/80e13f8a58fd">Andrey Ilnitskiy</a> for pointing out that we don’t need a ViewModel in this case — that’s a great insight. Here’s how we can reduce the size of our view by more than half by using AsyncSequence instead of an observed ViewModel, publishers, and other boilerplate.</p><pre>struct AsyncImage&lt;Content: View&gt;: View {<br>    @State var phase: AsyncImagePhase = .empty<br><br>    private let loader: ImageLoader<br>    private let url: URL<br>    private let content: (AsyncImagePhase) -&gt; Content<br>    <br>    init(url: URL, loader: ImageLoader = ImageLoaderImpl.shared, @ViewBuilder content: @escaping (AsyncImagePhase) -&gt; Content) {<br>        self.url = url<br>        self.loader = loader<br>        self.content = content<br>    }<br>    <br>    var body: some View {<br>        content(phase)<br>            .task {<br>                for await phase in loader.load(url: url).values {<br>                    self.phase = phase<br>                }<br>            }<br>    }<br>}</pre><p>Nice, clean, no unnecessary ViewModel — just how it should be. 🙂</p><p>P.S. Want to go deeper? Here are a few helpful links:</p><ul><li><a href="https://developer.apple.com/documentation/foundation/urlsession/processing_url_session_data_task_results_with_combine">Processing URL session data task results with Combine | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/combine/using-combine-for-your-app-s-asynchronous-code">Using Combine for Your App&#39;s Asynchronous Code | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/swiftui/asyncimage">AsyncImage | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/foundation/urlcache">URLCache | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/foundation/urlrequest/cachepolicy-swift.property/">cachePolicy | Apple Developer Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aae28f1a331" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI Animation: Creating an Interactive Button with TimelineView]]></title>
            <link>https://medium.com/@sviatoslav.kliuchev/swiftui-animation-creating-an-interactive-button-with-timelineview-bd12812c72e4?source=rss-f571c059e43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd12812c72e4</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[swiftui-animation]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Sviatoslav]]></dc:creator>
            <pubDate>Sat, 14 Dec 2024 17:53:37 GMT</pubDate>
            <atom:updated>2024-12-14T19:36:43.013Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi there! Since I started working on a side project in SwiftUI, I’ve been sharing my journey and the things I do every day while working on it.</p><p>While I was considering feauture that my app should have I decide it would be nice to have a button that shows an animation while my users are listening to sound. After some research and tinkering, I came up with this button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_HzjK1xDWxrthcCogy_LRA.gif" /><figcaption>Pic 1. Beautiful innit?</figcaption></figure><p>In this article, I’ll explain how it works and how you can do the same.</p><h3>Disclaimer</h3><p>This article is for entry-level developers, so if you’re a high-skilled 20-YOE-ex-FAANG ninja… you might still find it useful. 😊 Now, let’s get started to explore how to make this button!</p><h3>Step 0: Five (Guys 🍔) Bars</h3><p>Our animation is an “equalizer-like” effect, with a few bars that change their heights, imitating a real equalizer.</p><p>First, let’s create the view with bars:</p><pre>struct EqualizerView: View {<br>  @State private var animationValues: [CGFloat]<br>  private let barSize: CGSize<br>  <br>  init(barCount: Int = 5, barSize: CGSize = CGSize(width: 5, height: 30) {<br>    animationValues = EqualizerView.generateState(barCount)<br>    self.barSize = barSize<br>  }<br><br>  var body: some View {<br>    HStack(spacing: 4) {<br>        ForEach(0..&lt;animationValues.count, id: \.self) { index in<br>            RoundedRectangle(cornerRadius: 2)<br>                .frame(width: barSize.width, height: barSize.height)<br>        }<br>    }<br>      .frame(height: barSize.height)<br>      .padding()<br>      .background(.ultraThickMaterial)<br>      .cornerRadius(8)<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2fG7LRy9o6Nri0tImH9gfg.png" /><figcaption>Pic 2. It isn’t alive yet</figcaption></figure><p>Here, we created a view that takes the count of bars and their size. We placed it on ultra-thick material (SICK!) and added some padding all around.</p><h3>Step 1: Animation</h3><p>My goal was to show an endless animation that works only when sound is playing. As you may know, to animate anything, we need at least two things:</p><ol><li><strong>Values that change</strong> — obviously, we need to know what’s changing to create the animation.</li><li><strong>Mechanics</strong> that help us transition between states A → B.<br>Luckily, SwiftUI has a built-in solution, so we won’t need to reinvent the wheel.</li></ol><p>Let’s add this default mechanism to our view. We have two basic options to do that:</p><ul><li>withAnimation</li><li>The animation modifier.</li></ul><p>I recommend sticking with the second one because, in my opinion, it’s a more “declarative” way than calling a function randomly that performs some magic.</p><pre>struct EqualizerView: View {<br>  @State private var animationValues: [CGFloat]<br>  private let barSize: CGSize<br>  <br>  init(barCount: Int = 5, barSize: CGSize = CGSize(width: 5, height: 30) {<br>    animationValues = EqualizerView.generateState(barCount)<br>    self.barSize = barSize<br>  }<br><br>  var body: some View {<br>    HStack(spacing: 4) {<br>        ForEach(0..&lt;animationValues.count, id: \.self) { index in<br>            RoundedRectangle(cornerRadius: 2)<br>                .frame(width: barSize.width, height: barSize.height * animationValues[index])<br>                .animation(Animation.easeIn(duration: 0.4), value: animationValues[index])<br>        }<br>    }<br>      .frame(height: barSize.height)<br>      .padding()<br>      .background(.ultraThickMaterial)<br>      .cornerRadius(8)<br>  }<br>}</pre><p>Here, we added the modifier with one of the standard animations: easeIn. The animation works when animationValues[index] changes.</p><p>Now, we need to make these values change</p><h3>Step 2: State updating</h3><p>To update the state, we need to answer the questions:</p><h4>How should we do it?</h4><p>It’s simple: in our case, the heights of the bars depend on the data in animationValues. We just need to update this data with random (or specific) values.</p><p>Here’s a function that creates a random array of CGFloat values with a given size:</p><pre>private static func generateState(_ barCount: Int) -&gt; [CGFloat] {<br>    guard barCount &gt; 0 else {<br>        return []<br>    }<br>    return (0..&lt;barCount).map { _ in CGFloat.random(in: 0.3...1.0)  }<br>}</pre><blockquote>And to the folks who just thought about using Array(repeating: 0, count: 5), we can&#39;t use that because Array(repeating:count:) accepts a value, not a function. :), so we&#39;d have one random value for all the bars. Weird, right?</blockquote><h4><strong>When should we update the state?</strong></h4><p>This is where engineers start overcomplicating or oversimplifying things.<br>You’ll often come across these two main solutions:</p><p><strong>DispatchQueue: Bad Idea</strong></p><pre> var body: some View {<br>  SomeView<br>    .onAppear {<br>      startAnimating()<br>    }<br>    .onDisappear {<br>      isAnimating = false<br>    }<br>}<br><br>func startAnimating() {<br>  DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {<br>      // data updating is here<br>  <br>      // if isAnimation is false we shouldn&#39;t continue recursion<br>      if isAnimating {<br>          startAnimating()<br>      }<br>  }<br>}</pre><p>What’s wrong with this solution? It’s simple, and everyone understands how it works… <strong><em>Everything!</em></strong></p><ol><li>It’s recursion, and you need to control the main condition.</li><li>If you want to pause and resume the animation, you need to add some extra logic, which complicates things unnecessarily.</li></ol><blockquote>The rule of thumb — <strong>Don’t use DispatchQueue.main.asyncAfter </strong>if you can avoid it, there is planty of other things that cover your needs better.</blockquote><p><strong>Timer: Not so bad</strong></p><pre>.onAppear {<br>  timer = Timer.scheduledTimer(withTimeInterval: 0.4, repeats: true) { _ in  <br>    // data updating is here<br>  }<br>.onDisappear {<br>  timer?.invalidate() <br>}</pre><p>Honestly, there’s nothing wrong with this solution. It works, and it isn’t complicated.<br>However, if you want to stop and resume the animation, you’ll need to manage that with additional logic, which can complicate things.</p><p>It works fine for UIKit views, but since we’re building a declarative solution, it’s not the best solution. <em>However you can do it even worse!</em></p><p><strong>Bonus one: Put everything in ViewModel</strong></p><p>Sometimes people go overboard by moving view logic into the ViewModel for no reason, just to add test coverage to an already useless ViewModel—don’t be like these people!</p><pre>class ViewModel: ObservableObject {<br>  @Published var isAnimated: Bool = false<br>  @Published var animatedValues: [CGFLoat] = []<br>  private var timer: Timer?<br><br>  init() {}<br><br>  func startAnimating() {<br>    timer = Timer.scheduledTimer(withTimeInterval: 0.4, repeats: true) { _ in  <br>      // data updating is here<br>    }<br>  }<br>  func stopAnimating() {<br>    timer?.invalidate()<br>  }<br>}<br><br>struct EqualizerView: View {<br>  @ObservedObject var viewModel = ViewModel()<br>  <br>  var body: some View {<br>    someView<br>      .onAppear {<br>        viewModel.startAnimating()<br>      }<br>      .onDisappear {<br>        viewModel.stopAnimating() <br>      }<br>  }<br>}<br>  </pre><p>Already feeling like you’re on the way to becoming a $300k+ Software Engineer? Nope, you just made your life harder without any real benefit.</p><p>Let’s see how can we do it quicker and simpler.</p><p><strong>TimelineView</strong></p><p>The solution? TimelineView. A view that updates according to a schedule that you provide. Here’s the clean, simple solution:</p><pre>TimelineView(.animation(minimumInterval: interval, paused: paused)) { context in<br>    HStack(spacing: 4) {<br>        ForEach(0..&lt;animationValues.count, id: \.self) { index in<br>            RoundedRectangle(cornerRadius: 2)<br>                .frame(width: barSize.width, height: animationValues[index] * barSize.height)<br>                .animation(Animation.easeIn(duration: interval), value: animationValues[index])<br>        }<br>    }<br>    .frame(height: barSize.height)<br>    .onChange(of: context.date) { _, date in<br>        animationValues = EqualizerView.generateState(animationValues.count)<br>    }<br>}</pre><p>Simple, clear, declarative — everything we like and desire in our projects. With this solution, we don’t need to worry about recursion, timer invalidation, or any other complex logic. We just add the view, and it handles everything by itself.</p><p>How this solution works:</p><ol><li>The TimelineView updates its child views every &quot;interval&quot; (in our case, 0.4 seconds). It doesn’t update them if paused is true.</li><li>The onChange(of: context.date) modifier performs a closure every time context.date is updated, where new data is generated.</li></ol><h3>Fin.</h3><p>Here’s the full example of how to make the button from the first image:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7bdef23fd2f54516a6c11c49aa94c85/href">https://medium.com/media/c7bdef23fd2f54516a6c11c49aa94c85/href</a></iframe><p>Thank you for reading! Hope you learned something new, and stay tuned for more!</p><p><em>Useful links for those who want to dive deeper</em></p><ul><li><a href="https://developer.apple.com/documentation/swiftui/timelineview">TimelineView | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/swiftui/animation">Animation | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2024/10150/">SwiftUI essentials - WWDC24 - Videos - Apple Developer</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd12812c72e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create Instagram Like Animation]]></title>
            <link>https://medium.com/@sviatoslav.kliuchev/how-to-create-instagram-like-animation-f3e5d0a6a1d1?source=rss-f571c059e43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3e5d0a6a1d1</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Sviatoslav]]></dc:creator>
            <pubDate>Sat, 01 Jun 2024 21:59:25 GMT</pubDate>
            <atom:updated>2024-06-01T21:59:25.155Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*Lqk9-llppuU_fNbvU21d9g.png" /></figure><p>Hi there!</p><p>A few days ago, while scrolling my Instagram feed I discovered this amazing “Like” animation that happens when you double tap a photo. Though I am not quite a fan of the Instagram app, let me be honest with you — I was quite intrigued by the animation! I’ve recreated the effect and in this article, I’ll show you how to add this “Like” animation in your Flutter project!</p><h3>Disclaimer</h3><p>Look for this link in the article <strong>🧑‍💻 Run the code in Dartpad. </strong>It will allow you to run the example you see straight away in your browser. Might come in handy if you want to play with code!</p><h3><strong>What we are building</strong></h3><p>We will create a single-page app with an image and a Like animation from Instagram. The animation happens in several steps: user double taps a photo, a gradient-filled heart appears, it scales up and flies out of the screen. Sheer elegance!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*N3eHGl9DhxJk-Ycmth8WzA.gif" /><figcaption>The result we will achieve</figcaption></figure><p>So follow along and you’ll have a beautiful heart-popping effect in no time!</p><h3>Base project</h3><p>Here is a base project that you can use to start:</p><p><a href="https://dartpad.dev/?id=0b6465673f772e2ef7a328785b419084"><strong>🧑‍💻 Run the code in Dartpad.</strong></a><strong> </strong>(remember you can tap here to run the code?)</p><p>There is a bit of UI inside, but nothing works (yet).</p><h3>Step 0: Plan an app</h3><p>Before adding the Like feature to this base project, we need to get a grasp of these 3 concepts:</p><ol><li>How to detect Double Tap position.</li><li>How to put a Widget over all other widgets</li><li>How to animate a Widget.</li></ol><h3><strong>Step 1: Detect Double Tap position</strong></h3><p>First of all, a double tap is a gesture. Flutter has a widget for detecting gestures: GestureDetector.</p><p>Here is an example of how to use it:</p><pre>GestureDetector(<br>  /// a tap&#39;s callback<br>  onTap: () {<br>    print(&#39;it works when you are tapping on the child widget&#39;);<br>  },<br>  /// a widget which gestures are detected by GestureDetector<br>  child: Container()<br>);</pre><p>Some of the callbacks have additional details, like onTapUp. Most of these details contain gesture positions. Here is an example:</p><pre>GestureDetector(<br>  /// onTapUp callback provides details<br>  onTapUp: (details) {<br>    print(‘the tap position is ${details.globalPosition}’);<br>  },<br>  child: Container(),<br>);</pre><p>But as you know we need a position of a double tap, because it’s a gesture Instagram uses to start its Like animation. Sadly there isn’t any Double Tap callback that provides details in GestureDetector. No panic though, it’s easy to create our very own widget for this purpose. I’ve already added DoubleTapDetector to the base project, but if you want to know how it works, I suggest you have a look at this article:</p><p><a href="https://medium.com/@sviatoslav.kliuchev/how-to-get-details-on-ondoubletap-in-flutter-ce5e14621001">How to get details on onDoubleTap in Flutter</a></p><p>Let’s add DoubleTapDetector to Photo widget:</p><p><a href="https://dartpad.dev/?id=a3e749392c60449cf75a94d4fcf9b1fc"><strong>🧑‍💻 Run the code in Dartpad</strong></a><strong>. </strong>(tap, tap, tap)</p><pre>class Photo extends StatelessWidget {<br>  const Photo({super.key});<br><br>  @override<br>  Widget build(BuildContext context) =&gt; DoubleTapDetector(<br>        onDoubleTap: (details) =&gt; print(details.globalPosition),<br>        child: Image.network(<br>          &#39;https://i.postimg.cc/tgxsFtXt/IMG-4368.jpg&#39;,<br>          fit: BoxFit.cover,<br>        ),<br>      );<br>}=</pre><p>When you tap on the image (i.e. Photo widget), the position of your tap will be printed.</p><h3><strong>Step 2: Draw Over Fullscreen in Flutter</strong></h3><p>Now let’s draw a Widget over the Photo (as well as all other widgets). To achieve it, you can useStack, because Stack is a layout widget that allows you to put one widget over another. Here is an example of how it works:</p><p><a href="https://dartpad.dev/?id=e24ab22ac29b938fec391f01b912bab1"><strong>🧑‍💻 Run the code in Dartpad.</strong></a><strong> </strong>(by this time, you know what to do, right?)</p><pre>class ParentWidget extends StatelessWidget {<br>  const ParentWidget({super.key});<br>  Widget build(BuildContext context) {<br>    return Stack(children: [<br>      /// a widget on the background<br>      Container(color: Colors.yellow),<br><br>      /// a widget in the foreground<br>      Positioned(<br>        top: 10,<br>        left: 10,<br>        child: Container(<br>          color: Colors.blue,<br>          width: 30,<br>          height: 30,<br>        ),<br>      )<br>    ]);<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*tH8Q3Z6n6NsEQ7j516N3pw.png" /><figcaption>Stack + Positioned</figcaption></figure><p>As you can see in this example there is Positioned widget. This is a useful widget that allows you — as the name implies — to position its child at any place in Stack. To determine a position, set the top and left offsets.</p><p>However, for this app, we will use Overlay instead of using Stack directly. Why? Overlay allows us to put a widget everywhere on the screen, unlike Stack that only layouts its child widgets. Theoretically we can do it with Stack as well, but that will require wrapping the whole screen in Stack, creating some helper class to add a widget to the Stack and so on and so forth.. Trust me, we’d better stick to Overlay.</p><p>Here is an example of how to use overlay:</p><pre>/// get Overlay from the BuildContext<br>final overlay = Overlay.of(context);<br><br>final widgetThatWeWantToPutInOverlay = Container();<br><br>/// create OverlayEntry<br>final entry = OverlayEntry(<br> build: (context) =&gt; widgetThatWeWantToPutInOverlay<br>);<br><br>/// add OverlayEntry to Overlay <br>overlay.insert(entry);<br><br>/// remove entry from Overlay<br>entry.remove();</pre><p>Pretty simple, isn’t it? Let’s add this to our project. To do that, modify the onDoubleTap callback:</p><p><a href="https://dartpad.dev/?id=cc281e0d0b806956f577522049d2d1ef"><strong>🧑‍💻 Run the code in Dartpad.</strong></a></p><pre>onDoubleTap: (details) {<br>  /// widget sizes<br>  const width = 30.0;<br>  const height = 30.0;<br>  <br>  /// create offsets that place the center of widget<br>  /// to the center of DoubleTap.<br>  <br>  final left = details.globalPosition.dx - width / 2.0;<br>  final top = details.globalPosition.dy - height / 2.0;<br>  <br>  final entry = OverlayEntry(<br>    builder: (context) =&gt; Positioned(<br>      top: top,<br>      left: left,<br>      child: Heart(width: width, height: height),<br>    ),<br>  );<br>  <br>  Overlay.of(context).insert(entry);<br>},</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*LauGgtVwP_9DAj695NAfIg.gif" /><figcaption>Overlay + Positioned + DoubleTapDetector</figcaption></figure><p>Now wherever on the Photo you tap, a black square will pop up immediately!</p><h3><strong>Step 3: Plan an animation</strong></h3><p>Before we start implementing the animation, I want to give you a clear description of this animation. Please get familiar with my scheme:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2p19BUObcd7TcQDIiUGcpg.png" /></figure><p>I really like such schemes to describe animations as they are quick to read and easy to understand.</p><p>How you should read this:</p><ol><li>The line from 0.0 to 1.0 on the top of the scheme is a timeline of the animation.</li><li>Opacity, Rotation, Position, and Scale at the left side of the scheme are animations that are a part of the main animation.</li><li>Each one has its timeline describing where animation happens (numbers above the line), and the range of values of this animation (numbers below the line).</li></ol><p>This scheme is quite useful because it is very close to real Flutter code, and in a moment you will see why.</p><h3>Step 4. Implement animation</h3><p>Our animation is quite complex because it consists of several different animations. For cases like this, AnimationController is one of the best options.<br>Add AnimationController to the project. To do it, we need to create a widget that will work as “an animated heart”. Let’s name it PhotoLike, shall we?</p><pre>class PhotoLike extends StatefulWidget {<br> const PhotoLike({super.key});<br> State&lt;PhotoLike&gt; createState() =&gt; _PhotoLikeState();<br>}<br><br>class _PhotoLikeState extends State&lt;PhotoLike&gt; {<br> Widget build(BuildContext context) =&gt; const Heart();<br>}</pre><p>Now let’s add AnimationController to _PhotoLikeState and initialize it.</p><pre>class _PhotoLikeState extends State&lt;PhotoLike&gt; with SingleTickerProviderStateMixin {<br> /// the main animation duration<br> static const _animationDuration = Duration(seconds: 1);<br><br> late final AnimationController _controller;<br><br> void initState() {<br>  super.initState();<br>  // initalizing in initState because<br>  // AnimationController needs TickerProvider <br>  // that is _PhotoLikeState<br>  _controller = AnimationController(<br>   vsync: this,<br>   duration: _animationDuration,<br>  );<br> }<br><br> void dispose() {<br>  // it&#39;s important to dispose AnimationController<br>  // when it is not needed<br>  // in our case it on _PhotoLikeState.dispose()<br>  _controller.dispose();<br>  super.dispose();<br> }<br> <br> Widget build(BuildContext context) =&gt; const Heart();<br>}</pre><p>The code has got some comments, but there are a few things that I <em>need</em> to emphasize:</p><h4>Animation</h4><p>Animation is an illusion of motion. If a set of static images changes fast enough, they produce this illusion. If you interested in how it works, I really recommend this video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FV8A4qudmsX0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DV8A4qudmsX0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FV8A4qudmsX0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/69f8df604dc804fe49d8add3fa710887/href">https://medium.com/media/69f8df604dc804fe49d8add3fa710887/href</a></iframe><p>Modern screens support 120hz (that means they can change an image 120 times per second). In my opinion, this is a golden standart of frequency that provides smooth animation for the time being. If we want to have this level of smoothness in Flutter, we need to update the widgets tree based off frame changes. In Flutter, a class that can call callbacks on every frame is Ticker. AnimationController uses TickerProvider to get Ticker which AnimationController uses to update an animation value.</p><p>In the souce code above, _PhotoLikeState is TickerProvider as it implements SingleTickerProviderStateMixin.</p><p>Now, let’s try to animate opacity with AnimationController. To do it, let’s add Opacity to _PhotoLikeState build method and start the animation in initState():</p><p><a href="https://dartpad.dev/?id=f45e4faa824611f32b6443f4acc8eeff"><strong>🧑‍💻 Run the code in Dartpad.</strong></a></p><pre>void initState() {<br>    super.initState();<br>    _controller = AnimationController(<br>      vsync: this,<br>      duration: const Duration(seconds: 1),<br>    );<br><br>    _controller.addListener(() {<br>      setState(() {});<br>    });<br><br>    _controller.forward();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) =&gt; Scaffold(<br>        backgroundColor: Colors.white,<br>        body: Center(<br>          child: Opacity(<br>            opacity: _controller.value,<br>            child: Container(<br>              color: Colors.black,<br>              width: 100,<br>              height: 100,<br>            ),<br>          ),<br>        ),<br>      );</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*NfTfQBYzRNPbUsVRQtq_fg.gif" /><figcaption>Opacity + AnimationController.value</figcaption></figure><p>As you can see here, we added a listener to AnimationController to update state when AnimationController updates. Then, we started animation by calling _controller.forward(). In build method we use _controller.value as opacity in Opacity widget.</p><p>But what is the animation value?</p><p>Animation value is a value that represents an animation progress. It lies in the range between 0.0 and 1.0 (remember this timeline in the scheme above?). AnimationController calculates this value based off Duration and FPS of the screen your device has. So, for example, if your screen can show 120 FPS and your animation Duration is 1 second, AnimationController will update animation value every frame + 0.008. That means you will see 120 widgets with different Opacity that your brain will recognize as motion. Easy :).</p><p>While the animation in the previous example works, the Like animation is even more complex. As you can see on the scheme there are 4 different animations with even more different ranges.</p><p>Someone might say: “Okay, so we need to do some math that maps AnimationController.value to the value we need”. It’s true indeed, but wouldn’t it be better if we use excisting solutions instead of reinventing a wheel?</p><p>Let’s start with <strong>Opacity</strong>. To animate the opacity value from 0.0 to 1.0 and from 1.0 to 0.0, we need to use Tween.</p><p>Tween is a liner interpolation between begin and end. That means Tween calculates a needed value for animation by the current animation value.</p><p>Here is an example of how it works:</p><pre>final tween = Tween&lt;double&gt;(begin: 1, end: 100);<br><br>/// ( the middle of animation timeline )<br>double currentAnimationValue = 0.5;<br>print(tween.lerp(currentAnimationValue)); /// prints 50<br><br>currentAnimationValue = 0.8;<br>print(tween.lerp(currentAnimationValue)); /// prints 80<br><br>currentAnimationValue = 1.0;<br>print(tween.lerp(currentAnimationValue)); /// prints 100</pre><p>As you can see Tween can map any value that is provided by AnimationController to a value which coressponds with Tween.<br>To create more complex Tweens, there are additional classes: TweenSequence and TweenSequenceItem. TweenSequence is a class that combines Tweens and use their result in serial.</p><p>TweenSequenceItem is an item of TweenSequence that contains Tween and weight. Weight defines a percentage of duration. For example, if you put two TweenSequenceItems with the same weights, the first one will be used from 0.0 to 0.5 and the second one will be used from 0.5 to 1.0.</p><p>Let’s create TweenSequence that maps animation value as it is described in the scheme for <strong>Opacity</strong>:</p><pre>const appear = Tween&lt;double&gt;(begin: 0.0, end: 1.0);<br><br>const disappear = Tween&lt;double&gt;(begin: 1.0, end: 0.0); <br><br>const sequence = TweenSequence&lt;double&gt;([<br> TweenSequenceItem(tween: appears, weight: 50),<br> TweenSequenceItem(tween: disappear, weight: 50),<br>]);</pre><p>Now we have the TweenSequence that maps _controller animation to the opacity value that we need.</p><p>It’s time to add a new animation to _PhotoLikeState:</p><p><a href="https://dartpad.dev/?id=2d2411a99dc3ba06cf29e89f9dfd3ec3"><strong>🧑‍💻 Run the code in Dartpad.</strong></a></p><pre>  late final AnimationController _controller;<br>  late final Animation&lt;double&gt; _opacity;<br><br>  void initState() {<br>    super.initState();<br>    _controller = AnimationController(<br>      vsync: this,<br>      duration: const Duration(seconds: 2),<br>    );<br><br>    _controller.addListener(() {<br>      setState(() {});<br>    });<br>    <br>    final appear = Tween&lt;double&gt;(begin: 0.0, end: 1.0);<br>    final disappear = Tween&lt;double&gt;(begin: 1.0, end: 0.0); <br>    <br>    final sequence = TweenSequence&lt;double&gt;([<br>     TweenSequenceItem(tween: appear, weight: 50),<br>     TweenSequenceItem(tween: disappear, weight: 50),<br>    ]);<br><br>    /// create an animation with _controller as a parent animation<br>    _opacity = sequence.animate(_controller);<br><br>    _controller.forward();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) =&gt; Scaffold(<br>        backgroundColor: Colors.white,<br>        body: Center(<br>          child: Opacity(<br>            opacity: _opacity.value,<br>            child: Container(<br>              color: Colors.black,<br>              width: 100,<br>              height: 100,<br>            ),<br>          ),<br>        ),<br>      );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*KPeh9QVKgtRYoZepZ5qvLw.gif" /><figcaption>Opacity + Animation + Tween + TweenSequence</figcaption></figure><p>In this code, we created a new animation _opacity controlled by AnimationController that means value of opacity changes when AnimationController value changes. But unlike _controller.value, _opacity.value is in range 0.0 -&gt; 1.0 -&gt; 0.0.</p><h3><strong>Scale</strong></h3><p>Let’s implement scale animation the same way:</p><p><a href="https://dartpad.dev/?id=afc4bb8ec95d7fca07bdc89fdf81d70a"><strong>🧑‍💻 Run the code in Dartpad.</strong></a></p><pre>  late final AnimationController _controller;<br><br>  late final Animation&lt;double&gt; _scale;<br><br>  void initState() {<br>    super.initState();<br>    _controller = AnimationController(<br>      vsync: this,<br>      duration: const Duration(seconds: 2),<br>    );<br><br>    _controller.addListener(() {<br>      setState(() {});<br>    });<br><br>    final sequence = TweenSequence&lt;double&gt;([<br>      TweenSequenceItem(tween: Tween(begin: 0.5, end: 1.0), weight: 50),<br>      TweenSequenceItem(tween: Tween(begin: 1.0, end: 1.5), weight: 50),<br>    ]);<br><br>    /// create an animation with _controller as a parent animation<br>    _scale = sequence.animate(_controller);<br><br>    _controller.forward();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) =&gt; Scaffold(<br>        backgroundColor: Colors.white,<br>        body: Center(<br>          child: Transform.scale(<br>            scale: _scale.value,<br>            child: Container(<br>              color: Colors.black,<br>              width: 100,<br>              height: 100,<br>            ),<br>          ),<br>        ),<br>      );</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*E4odlrUgFYpuHnhZ_CCpxA.gif" /><figcaption>Transform.scale + TweenSequence + Tween</figcaption></figure><p>Here we used Transform.scale to change the size of a child Widget. Quite similar to Opacity, except for the different ranges Tweens have.</p><p><strong>Rotation</strong></p><p>Look at the scheme once again, Rotation is a slightly different step. Rotation animation starts from 0.0 to 0.5 of the main animation timeline and does nothing after that. <em>Doing nothing</em> means the animation value doesn’t change after that.</p><p><a href="https://dartpad.dev/?id=2e1029f3068b01fa8d042351b5e1eb4d"><strong>🧑‍💻 Run the code in Dartpad.</strong></a></p><pre>late final AnimationController _controller;<br><br>  late final Animation&lt;double&gt; _rotation;<br><br>  void initState() {<br>    super.initState();<br>    _controller = AnimationController(<br>      vsync: this,<br>      duration: const Duration(seconds: 2),<br>    );<br><br>    _controller.addListener(() {<br>      setState(() {});<br>    });<br><br>    // a random angle of +- 45 degrees<br>    final beginAngle = Random.secure().nextDouble() - 0.5;<br>    <br>    const endAngle = 0.0;<br><br>    final sequence = TweenSequence&lt;double&gt;([<br>      TweenSequenceItem(<br>        tween: Tween(begin: beginAngle, end: endAngle),<br>        weight: 50,<br>      ),<br>      TweenSequenceItem(<br>        tween: ConstantTween(endAngle),<br>        weight: 50,<br>      ),<br>    ]);<br><br>    /// create an animation with _controller as a parent animation<br>    _rotation = sequence.animate(_controller);<br><br>    _controller.forward();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) =&gt; Scaffold(<br>        backgroundColor: Colors.white,<br>        body: Center(<br>          child: Transform.rotate(<br>            angle: _rotation.value,<br>            child: Container(<br>              color: Colors.black,<br>              width: 100,<br>              height: 100,<br>            ),<br>          ),<br>        ),<br>      );</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*B2oUC2nTbHFgDLDUFo8C0g.gif" /><figcaption>Transform.rotate + TweenSequence + Tween</figcaption></figure><p>Here’s how the angle is changing its value randomly in a range between -45 and 45 degrees (-0.5 to 0.5). As you can see we used ConstantTween to create a Tween that returns the same result.</p><h4>Position</h4><p>Position animation can be created with the same classes that we used before, but there is one problem. The heart should appear at the place where the user tapped but then it should fly out of the screen. We need to know the distances and mind screen bounds.</p><p>To move the Widget out of the screen, we will use Transform.translate. It moves a child Widget with the given Offset. Let’s do some calculations:</p><p><strong>Top offset calculations:</strong></p><pre>// animation should start from the current widget position<br>final beginTopOffset = 0.0;<br><br>/// it ends above the top of the screen. It means the top offset should be equal to  <br>final endTopOffset = -widget._position.dy</pre><p><strong>Left offset calculations:</strong></p><pre>// animation should start from the current widget position<br>final beginLeftOffset = 0.0;<br><br>// endLeft is random point between the wiget current position <br>// the center of the screen<br>// get screen width:<br>final screenWidth = MediaQuery.of(context).size.width;<br><br>// get the centre point<br>final centerX = screenWidth / 2.0;<br><br>// get the distance between the centre of the screen and the widget position.<br>final distance = centerX - widget._position.dx;<br><br>// multiply distance with a random number between 0.0 and 1.0 <br>final randomPoint = distance * Random.secure().nextDouble();<br><br>final endLeftOffset = randomPoint;</pre><p>And now we bump into this issue: we can’t use context in void initState() and we lack some data to make Tween. However, we can create Tween without the end argument and set it later (when we will have all the necessary info).</p><p>As you may know, we can use context in two places of State&lt;StatefulWidget&gt;:</p><ol><li>Widget build(BuildContext context) not preferable except for building widgets tree.</li><li>void didChangeDependencies() — the very place where it should be done, because MediaQuery is a dependency we need.</li></ol><p>So let’s put the calculations to void didChangeDependencies() and create the position animation.</p><p><a href="https://dartpad.dev/?id=34519dfdc86ff787dc9130379d5c2633"><strong>🧑‍💻 Run the code in Dartpad.</strong></a></p><pre>late final AnimationController _controller;<br><br>  late final Animation&lt;Offset&gt; _position;<br>  late final Tween&lt;Offset&gt; _positionTween;<br><br>  void initState() {<br>    super.initState();<br><br>    _controller = AnimationController(<br>      vsync: this,<br>      duration: const Duration(seconds: 2),<br>    );<br><br>    _controller.addListener(() {<br>      setState(() {});<br>    });<br><br>    _positionTween = Tween(begin: Offset.zero);<br><br>    final sequence = TweenSequence&lt;Offset&gt;([<br>      TweenSequenceItem(<br>        tween: ConstantTween(Offset.zero),<br>        weight: 50,<br>      ),<br>      TweenSequenceItem(<br>        tween: _positionTween,<br>        weight: 50,<br>      ),<br>    ]);<br><br>    /// create an animation with _controller as a parent animation<br>    _position = sequence.animate(_controller);<br><br>    _controller.forward();<br>  }<br><br>  void didChangeDependencies() {<br>    super.didChangeDependencies();<br>    final screenWidth = MediaQuery.of(context).size.width;<br>    final screenCenter = screenWidth / 2.0;<br><br>    final distance = widget._position.dx - screenCenter;<br>    final leftOffset = distance * Random.secure().nextDouble();<br><br>    final topOffset = widget._position.dy;<br><br>    _positionTween.end = Offset(topOffset, leftOffset);<br>  }<br><br>  @override<br>  Widget build(BuildContext context) =&gt; Scaffold(<br>        backgroundColor: Colors.white,<br>        body: Stack(<br>          children: [<br>            Positioned(<br>              top: widget._position.dy,<br>              left: widget._position.dx,<br>              child: Transform.translate(<br>                offset: _position.value,<br>                child: Container(<br>                  color: Colors.black,<br>                  width: 100,<br>                  height: 100,<br>                ),<br>              ),<br>            ),<br>          ],<br>        ),<br>      );</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*6-kyTSY3EHG2m2UwScdIUA.gif" /><figcaption>Transform.translate + Tween + TweenSequence</figcaption></figure><h4>Combine animations.</h4><p>Whew! The previous examples show each animation seperately. Let’s modify original project and combine them all.</p><p>The listing is too long to add to the article, please use Dartpad.</p><p><strong>🧑‍💻</strong><a href="https://dartpad.dev/?id=7d590d37bead241e09b99117e45b1865"><strong> Run the code in Dartpad.</strong></a></p><p><strong>💾</strong><a href="https://gist.github.com/kliuchev/7d590d37bead241e09b99117e45b1865"><strong> Link to source code in Github</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*GVb2EH6RSqOpOMKVnrUUGQ.gif" /></figure><h3><strong>Step 5. Hearts</strong></h3><p>In the previous step, we did the animation but it was a black square that we animated! And, to be honest, you can leave it as it is if you appreciate Malevich more than Instagram.</p><p>Though to wrap it all up, here is the code to replace the black square with the heart:</p><p><a href="https://dartpad.dev/?id=73e1fb75d837b8bb2ebd838417ce3c05"><strong>🧑‍💻 Run the code in Dartpad.</strong></a></p><pre>class Heart extends StatelessWidget {<br>  const Heart({<br>    super.key,<br>    Size? size,<br>  }) : _size = size;<br><br>  final Size? _size;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return CustomPaint(<br>      painter: const HeartPainter(),<br>      size: _size ?? Size.zero,<br>    );<br>  }<br>}<br><br>class HeartPainter extends CustomPainter {<br>  const HeartPainter({this.stockWidth = 5});<br><br>  final double stockWidth;<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final paint = Paint()<br>      ..style = PaintingStyle.fill<br>      ..shader = const LinearGradient(<br>        colors: [Colors.red, Colors.purple],<br>        stops: [0.2, 1],<br>        transform: GradientRotation(0.3 * 3.14),<br>      ).createShader(Rect.fromLTWH(0, 0, size.width, size.height));<br><br>    final path = createHeartShapePath(size);<br><br>    canvas.drawPath(path, paint);<br>  }<br><br>  @override<br>  bool shouldRepaint(covariant CustomPainter oldDelegate) =&gt; true;<br><br>  static Path createHeartShapePath(Size size) {<br>    return Path()<br>      ..moveTo(size.width / 2, size.height * 0.35)<br>      ..cubicTo(0.2 * size.width, size.height * 0.1, -0.25 * size.width,<br>          size.height * 0.6, 0.5 * size.width, size.height)<br>      ..cubicTo(1.25 * size.width, size.height * 0.6, 0.8 * size.width,<br>          size.height * 0.1, size.width / 2, size.height * 0.35)<br>      ..close();<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*N3eHGl9DhxJk-Ycmth8WzA.gif" /><figcaption>The result</figcaption></figure><p>By the way, Heart is a custom-painted widget and if you want to know how create one, let me kindly suggest this read:</p><p><a href="https://medium.com/@sviatoslav.kliuchev/how-to-draw-a-custom-icon-in-flutter-93b2a510d300">How to draw a custom icon in Flutter</a></p><h3>Fin.</h3><p>Congratulations! Now you’ve learnt Animation basics, what is AnimationController, how to combine Tween, how to animate widgets and most importantly how to create<strong> Instagram-like animation</strong> ❤️!</p><p>If you want to know more about Flutter and software development in general, subscribe to receive my articles on Medium and give me a clap or two ( 50 would be so exciting 👏 ) it keeps me motivated to write more.</p><p>Also, you can follow me on Instagram!</p><p><strong>📷 </strong><a href="https://www.instagram.com/s.s.kliuchev/"><strong>https://www.instagram.com/s.s.kliuchev/</strong></a></p><p>No idea why on Earth you’d want to do that, but since this article is all about Instagram, don’t hold yourself back :)</p><p>For those of you eager to learn and know more about animation, I highly recommend these links:</p><ol><li>Read official documentation about all widgets and classes that we’ve used in this article: <a href="https://api.flutter.dev/flutter/animation/AnimationController-class.html">AnimationController</a>, <a href="https://api.flutter.dev/flutter/widgets/AnimatedBuilder-class.html">AnimatedBuilder</a>, <a href="https://api.flutter.dev/flutter/widgets/Transform-class.html">Transform</a>, <a href="https://api.flutter.dev/flutter/animation/Tween-class.html">Tween</a>, <a href="https://api.flutter.dev/flutter/animation/TweenSequence-class.html">TweenSequence</a>, <a href="https://api.flutter.dev/flutter/animation/TweenSequenceItem-class.html">TweenSequenceItem</a>, <a href="https://api.flutter.dev/flutter/widgets/FadeTransition-class.html">FadeTransition</a>.</li><li><a href="https://docs.flutter.dev/ui/animations">Introduce to animation</a></li><li>Watch this video <a href="https://www.youtube.com/watch?v=wnARLByOtKA">Flutter Europe: Animations in Flutter done right</a></li><li>And read my next articles because some of them will describe animation more :).</li></ol><p>Stay tuned gang!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3e5d0a6a1d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to draw a custom icon in Flutter]]></title>
            <link>https://medium.com/@sviatoslav.kliuchev/how-to-draw-a-custom-icon-in-flutter-93b2a510d300?source=rss-f571c059e43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/93b2a510d300</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Sviatoslav]]></dc:creator>
            <pubDate>Wed, 22 May 2024 18:29:38 GMT</pubDate>
            <atom:updated>2024-05-22T18:29:38.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DqBVMDDRKsewkLPvS_W18w.png" /></figure><p>Hi!</p><p>Today, I’m going to show you how to draw a heart icon in Flutter.</p><p>First of all, you may know that Flutter has a set of icons that you can use for various purposes. For instance, there’s the Icons.favorite icon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Snb7elyRXqbHDnLaMzyq2g.png" /><figcaption>Icons.favorite</figcaption></figure><p>While it looks good, it’s also so overused, and we’ve seen it thousands of times in apps. So let’s create something beautiful and unique ourselves. In this article, we will create three types of hearts: “Outlined”, “Red”, and “Gradient”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJzV-M25jwrGcKhzS_KUUg.png" /><figcaption>Three hearts</figcaption></figure><h3>How to draw in Flutter</h3><p>As you know, all UI elements in Flutter, including every button and every text, are drawn on a canvas. Each widget that displays something on the screen contains instructions on how to draw it on the canvas using <em>primitives</em>.</p><p>Flutter developers have made our lives easier by creating a vast number of widgets for every occasion. However, sometimes we need something custom while developing applications. In such cases, two classes come to our rescue: CustomPaint and CustomPainter.</p><p>CustomPaint is a widget where you can set your own instructions for what should be drawn on the canvas.</p><p>CustomPainter is the class that actually contains these instructions.</p><p>Here is a simple example of how to draw a rectangle using CustomPaint and CustomPainter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bdfb7e6c8411d61e23360150dc7649f/href">https://medium.com/media/3bdfb7e6c8411d61e23360150dc7649f/href</a></iframe><p><a href="https://dartpad.dev/?id=fbf159920ab655fa958366bc4c6c7b4a"><strong>Run the code</strong></a></p><p>Let’s dive into the details. As you can see, a CustomPaint widget has been added to the widget tree with two parameters:</p><ul><li>painter — An object that contains instructions on what and how to draw.</li><li>size — Widget dimensions. This is an optional parameter; the size can be determined by the parent or child widget</li></ul><p>Starting from line 39, a class is declared that is a child of CustomPainter — RectPaint. It has two methods:</p><ul><li>void paint(Canvas canvas, Size size) — this method is called every time an element needs to be drawn on the canvas.</li><li>void shouldRepaint(covariant CustomPainter oldDelegate) — this method determines whether an element should be redrawn.</li></ul><h4>About shouldRepaint and Optimization</h4><p>Flutter decides whether to call the paint method or use its previous result basing off many parameters. We can conditionally divide these parameters into two types:</p><ul><li><strong>External factors</strong> — for example, changing the size of the container.</li><li><strong>Internal factors</strong> — for example, if our CustomPainter was specified with a color, and the color has changed, it is necessary to redraw. Each redraw adds additional load, so <strong>avoid</strong> it whenever possible, and use it whenever absolutely necessary. However, for when your interface is not complex, remember: <strong>premature optimization is the root of all evil</strong>. It’s better to make an MVP of your application and then improve it, rather than never finish it, aiming for perfect performance from the start.</li></ul><p>For now, we will omit this function and will just set the return value as true or false for simplicity in this article.</p><h4>The paint Method</h4><p>The paint method contains two parameters:</p><ul><li>Canvas canvas — this is the canvas on which we draw.</li><li>Size size — this is the size of the surface on which we are drawing.</li></ul><p>The Canvas class has several methods for drawing different shapes, such as lines, rectangles, ovals, and paths. Most of these methods require data about what we are drawing and how we are doing it. The Paint object is responsible for the latter.</p><p>In our example, a blue filled square is displayed on the screen. To make it blue and filled, we’ve created a Paint object like this:</p><pre>final paint = Paint()<br>  ..color = Colors.blue  // set a color<br>  ..style = PaintingStyle.fill; // set painting style</pre><p>Next, we need to draw the square itself using the coordinates and the Paint object that we made earlier.</p><pre>/// Create a rect based on size of canvas<br>final rect = Rect.fromLTWH(0, 0, size.width, size.height);<br><br>/// Draw the rect on the canvas using Paint object<br>canvas.drawRect(rect, paint);</pre><p>Now that we understand how rendering works, let’s try to make the square not blue, but filled with a yellow-blue gradient. To do this, we need to slightly modify the Paint object. Instead of setting a color, we&#39;ll specify the desired gradient:</p><pre>final paint = Paint()<br>  ..style = PaintingStyle.fill // keep this style of painting<br>  ..shader = const LinearGradient( // create a gradient<br>    colors: [Colors.lightBlue, Colors.yellow], // set colours <br>  ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)) // Create a shader based on LinearGradient;</pre><p><a href="https://dartpad.dev/?id=bf33cc426380c740dcca272d5ba9c2ba"><strong>Run the code</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h3js5i907KR2sVynUEiKpg.png" /><figcaption>CustomPaint + RectPainter + Gradient</figcaption></figure><h4>Stroke</h4><p>The Paint object can not only fill the shapes we&#39;ve drawn, but also stroke them. To do this, let&#39;s change the Paint settings:</p><pre>final paint = Paint()<br>      ..style = PaintingStyle.stroke // Change the style to stroke<br>      ..strokeWidth = 5 // Set the stroke&#39;s width<br>      ..shader = const LinearGradient(<br>        colors: [Colors.lightBlue, Colors.yellow],<br>      ).createShader(Rect.fromLTWH(0, 0, size.width, size.height));</pre><p><a href="https://dartpad.dev/?id=e85cf1516f55886b5db484a9ae19a044"><strong>Run the code</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_8elVgvrUk8DhNoZDqL7Q.png" /><figcaption>CustomPaint + RectPainter + Gradient + PaintingStyle.stroke</figcaption></figure><p>Here, we changed the painting style and set an additional parameter, strokeWidth, which defines the width of the stroke. Now, we have all three Paint objects that we can use to draw the hearts. Remember why we&#39;re here? 🙂.</p><h3>Path</h3><p>To draw shapes more complex than a rectangle, let’s use the Canvas.drawPath method. This method still takes Paint as a parameter, but in addition, it needs a Path. The official documentation defines Path as a complex one-dimensional subset of the plane. However, I offer you another definition:</p><blockquote>Path is an object that contains a set of rules which allow us to draw any shape on a canvas. A Path can contain both primitive objects like lines and more complex ones like curves.</blockquote><p>Here is the path needed to draw a heart:</p><pre><br>final path = Path()<br>  ..moveTo(size.width / 2, size.height * 0.35)<br>  ..cubicTo(0.2 * size.width, size.height * 0.1, -0.25 * size.width,<br>      size.height * 0.6, 0.5 * size.width, size.height)<br>  ..cubicTo(1.25 * size.width, size.height * 0.6, 0.8 * size.width,<br>      size.height * 0.1, size.width / 2, size.height * 0.35)<br>  ..close();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZMqQxTyNVoFavVyPYFwIg.png" /><figcaption>The result: A heart drawn with Path</figcaption></figure><p><a href="https://dartpad.dev/?id=ff77f67b51350a49eacc26ba7e691e8c"><strong>Run the code</strong></a></p><p>At first glance, it looks like a pile of random numbers and weird method calls. However, it’s only partially true (a lil disclaimer for you: these numbers were generated by a local AI model since I’m too lazy to calculate them myself). But all the methods are correct. Here is a description for each:</p><ul><li>Path.moveTo — this method sets the starting point of the path.</li><li>Path.close — this method connects the current point to the first point of the path.</li><li>Path.cubicTo — adds a cubic Bezier segment that curves from the current point to the given point (x3, y3), using the control points (x1, y1) and (x2, y2). To be honest, I couldn’t really wrap my head around it until I saw it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*FLCtBit6n5G1yFUH_KS_mg.png" /><figcaption>The image from documentation</figcaption></figure><p>Here is a GIF showing how each method works step by step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*rFKnZ-Cqe9gmiUXNC4j6pQ.gif" /><figcaption>Drawing a heart line by line</figcaption></figure><h3>The result</h3><p>Now you have all the information you need to draw a heart like the one in the first picture of this article. Here is the full source code of the project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35c4a007b668426e182091d01f6fd9ea/href">https://medium.com/media/35c4a007b668426e182091d01f6fd9ea/href</a></iframe><p><a href="https://dartpad.dev/?id=0b3003fc7d871fd2ec35433bc839d7a3"><strong>Run the code</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJzV-M25jwrGcKhzS_KUUg.png" /><figcaption>The hearts</figcaption></figure><h3>Conclusion</h3><p>Today, you’ve learned how to draw custom UI elements in Flutter using CustomPaint and CustomPainter, and you created beautiful heart icons! I hope you enjoyed this tutorial and found the results satisfying. And give me a few claps, if haven&#39;t done that yet 😊.</p><p>If you want to learn more about custom painting in Flutter, it’s time to dive into the official documentation. Start here: <a href="https://api.flutter.dev/flutter/widgets/CustomPaint-class.html"><strong>CustomPaint</strong></a> and explore as deeply as you need.</p><p>Bye.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93b2a510d300" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get details on onDoubleTap in Flutter]]></title>
            <link>https://medium.com/@sviatoslav.kliuchev/how-to-get-details-on-ondoubletap-in-flutter-ce5e14621001?source=rss-f571c059e43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce5e14621001</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Sviatoslav]]></dc:creator>
            <pubDate>Wed, 22 May 2024 18:00:14 GMT</pubDate>
            <atom:updated>2024-05-22T18:00:14.466Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n0CgqfDeaLo2LB2j" /><figcaption>Photo by <a href="https://unsplash.com/@rmrdnl?utm_source=medium&amp;utm_medium=referral">Daniel Romero</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello!</p><p>Recently, I wrote an article about how to create a “like” animation similar to Instagram’s. The idea is that when you double-tap anywhere on a photo, a heart appears under your finger and then flies off the screen. It looks great, but I encountered a problem: GestureDetector I was using to detect gestures doesn&#39;t have details for the onDoubleTap event and lacks an onDoubleTapUp event that could have this data.</p><p>So, I had to create my own implementation of the onDoubleTap detector.</p><p>Here’s the code:</p><pre>class DoubleTapDetector extends StatefulWidget {<br>  const DoubleTapDetector({<br>    super.key,<br>    required Widget child,<br>    required GestureTapDownCallback onDoubleTap,<br>  })  : _child = child,<br>        _onDoubleTap = onDoubleTap;<br><br>  final Widget _child;<br>  final GestureTapDownCallback _onDoubleTap;<br><br>  @override<br>  State&lt;DoubleTapDetector&gt; createState() =&gt; _DoubleTapDetectorState();<br>}<br><br>class _DoubleTapDetectorState extends State&lt;DoubleTapDetector&gt; {<br>  TapDownDetails? _tapDownDetails;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return GestureDetector(<br>      onDoubleTapCancel: () =&gt; _tapDownDetails = null,<br>      onDoubleTapDown: (details) =&gt; _tapDownDetails = details,<br>      onDoubleTap: () {<br>        if (_tapDownDetails == null) return;<br>        widget._onDoubleTap(_tapDownDetails!);<br>      },<br>      child: widget._child,<br>    );<br>  }<br>}</pre><p>Let’s break down the implementation.</p><p>As you can see, there is onDoubleTapDown method that contains the necessary details. The widget stores this data in the state, and then onDoubleTap can provide this data. Also we clean this data on onDoubleTapCancel.</p><p>To use this widget, wrap any widget like this:</p><pre>DoubleTapDetector(<br>  child: const SizedBox.square(<br>    dimension: 100,<br>  ),<br>  onDoubleTap: (details) =&gt; print(&#39;Double details: $details&#39;),<br>);</pre><p>And that’s it! A simple solution that works.</p><p>If this article is useful for you, don’t hold back — give it a clap! 😊</p><p>Bye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce5e14621001" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>