<?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 Valentyna Polienova on Medium]]></title>
        <description><![CDATA[Stories by Valentyna Polienova on Medium]]></description>
        <link>https://medium.com/@m1nori?source=rss-943a64474b36------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*73oUTeOQKvM8-1k90dJHsQ.jpeg</url>
            <title>Stories by Valentyna Polienova on Medium</title>
            <link>https://medium.com/@m1nori?source=rss-943a64474b36------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 19:23:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@m1nori/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What a test audit taught us about working with coding agents]]></title>
            <link>https://medium.com/@m1nori/what-a-test-audit-taught-us-about-working-with-coding-agents-4392165d7b4b?source=rss-943a64474b36------2</link>
            <guid isPermaLink="false">https://medium.com/p/4392165d7b4b</guid>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[developer-productivity]]></category>
            <dc:creator><![CDATA[Valentyna Polienova]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 10:06:01 GMT</pubDate>
            <atom:updated>2026-10-22T10:06:01.785Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Faster Flutter tests, stronger checks, and two small skills to help agents repeat the good work.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*APJl9mGaKE6tpp_lS63cFQ.png" /><figcaption>Test runtime fell from 23.67 to 12.59 seconds, about 47% less time, with 1,447 tests passing. Based on local benchmark medians.</figcaption></figure><p>Our Flutter app had <strong>1,451 runnable tests</strong> when we measured it. The suite was growing, and we wanted to understand its value and cost.</p><p>Which tests would catch a real bug? Which tests were slow? Could we make them cheaper without losing useful checks?</p><p>We removed four weak cases. But removing those cases alone had shown no clear speed improvement in an earlier comparison. The biggest gain came from changing tests that waited for real time to pass.</p><p>After the full cleanup, our local run went from <strong>a median of 23.67 seconds to 12.59 seconds</strong>. All 1,447 remaining cases passed.</p><p>The work also gave us useful rules for coding agents. We started turning these lessons into two skills: one for writing tests and one for reviewing existing tests.</p><h3>Start with a question about bugs</h3><p>Before judging a test, we read the code it tested. We also looked at nearby tests. We wanted to answer one question:</p><p><strong>What realistic bug would make this test fail?</strong></p><p>This helped us avoid quick decisions based only on test size or style. A short test may protect an important business rule. A test with mocks may check a useful error path. A widget test may catch a problem in the screen that a unit test cannot see.</p><p>We paid special attention to data shown on screen, object identity, saved data, login, and results that arrive later.</p><p>We counted the whole main suite, but we reviewed selected candidates in detail. We did not prove that every remaining test was needed. Most of the tests we reviewed were worth keeping.</p><h3>A test should send the result it claims to check</h3><p>One data-loading test checked what happened after two requests. Its name said that the second request cancelled the first and used only the new result.</p><p>The test waited half a second. But the first stream never sent a result.</p><p>It checked the new result, but it did not check what happened when an old result arrived late. We changed the test to control both streams.</p><p>This is the sequence in simple form, not runnable Dart code:</p><pre>Start request A.<br>Start request B.<br>Check that A&#39;s subscription is cancelled.<br>Send B&#39;s result: [1].<br>Send A&#39;s late result: [99].<br>Check that the state still contains [1].</pre><p>The different values matter. If both requests returned the same list, a wrong update could be hard to notice.</p><p>We could remove the real wait because the test now controlled event delivery. It also checked the old subscription directly.</p><p>This pattern is useful for search, filters, and any screen where users can start a new request before the old one finishes.</p><h3>Move the clock instead of waiting</h3><p>Our search and filter tests used real waits for a debounce timer. Debounce means waiting briefly after the user stops typing before starting a search.</p><p>The app used a 600 ms delay. Tests waited for that delay to pass. One filter test used two waits of 1,600 ms.</p><p>We replaced these waits with fakeAsync. It lets a test move time forward without waiting for the same time in the real world.</p><p>We also checked both sides of the deadline:</p><pre>Enter a search term.<br>Move the test clock forward by 599 ms.<br>Check that no search has started.<br>Move the clock forward by 1 ms.<br>Check that the search starts with the correct input.</pre><p>The first check is important. If we only checked the final result, the test could still pass if someone removed the debounce completely.</p><p>Other tests kept checks for rapid typing and search reset. Making them faster was useful only if those checks stayed.</p><p>In Flutter, the timer must start inside the fakeAsync callback. A timer started earlier still uses real time. Widget tests have their own clock rules, so we keep separate examples for those tests.</p><h3>Remove tests for a clear reason</h3><p>We found four cases with little useful protection.</p><p>Two checked a false flag that a test helper had already supplied. Another checked a switch written only inside the test. The last compared two identical constant objects.</p><p>That equality example needed care. In Dart, identical constants can be the same object. Comparing them did not show that equality handled the field named in the test. A separate test still checked that changing the relevant field made the objects unequal.</p><p>For each removal, we checked what protection would remain. We did not set a target number of tests to delete.</p><p>This is an old testing problem. Google’s article about <a href="https://testing.googleblog.com/2015/01/testing-on-toilet-change-detector-tests.html">change-detector tests</a> explains how a test can repeat the code without checking the behaviour we need.</p><p>Still, a pattern is only a reason to look closer. Mock calls can be the correct thing to check. Two similar tests can protect different parts of an app. Neither should be removed just because it looks simple.</p><h3>Measure the same thing before and after</h3><p>Our CI uses Very Good CLI to group test files into one generated runner. A normal Flutter test run uses a different setup. We needed to account for that before comparing times.</p><p>For the local comparison, we used the pinned CLI’s grouping template in a temporary runner outside the repository. Both versions used Flutter 3.44.1 through FVM, seed 20261015, and the same -j 4 setting. A seed is the number that lets us repeat the same random order.</p><p>For each version, we ran one warm-up, then three measured runs. The median is the middle result of those three runs.</p><p><strong>The results were:</strong></p><ul><li>Before: 1,451 cases, median 23.67 seconds. Runs ranged from 23.58 to 23.86 seconds.</li><li>After: 1,447 cases, median 12.59 seconds. Runs ranged from 12.43 to 13.97 seconds.</li><li>Difference: 11.08 seconds, or about 47% less time in this local comparison.</li></ul><p>We checked the executed case names. Only the four intended cases disappeared. All remaining cases passed in each measured run.</p><p>These were laptop results. Background load was not fully controlled. The timing also excluded the CLI wrapper’s startup and runner generation. We have not measured the saving on hosted CI.</p><p>We used total run time for the comparison. Adding individual test times together would not give a reliable saving when tests run in parallel.</p><h3>Give agents a clear way to work</h3><p>After the cleanup, we started putting the lessons into two agent skills. A skill is a small set of reusable instructions for a task.</p><p>The first, write-tests, helps an agent add or improve tests. The second, audit-tests, helps it review tests that already exist.</p><p>Keeping the jobs separate makes the scope easier to understand. A request for one bug-fix test should not start a full suite audit. An audit should produce a report before cleanup begins.</p><p>Here is a short example of the guidance we want in the writing skill:</p><pre>Before adding a test:<br>- Name a realistic bug it should catch.<br>- Read nearby tests and find what protection is missing.<br>- Use data that makes wrong behaviour visible.<br>- Control timers and the order of async results.<br>- For a bug fix, check that it fails without the fix.<br>- Do not weaken a test only to make the run pass.</pre><p>If a test fails, the agent needs to understand why. The code may be wrong. The expected behaviour may have changed. The agent should report unclear cases instead of quietly changing the expected result.</p><p>The audit skill needs a different output: test counts, timings, evidence, and a clear recommendation. A useful review may recommend keeping a test, making it cheaper, merging it, or removing it. It should also be able to say, “There is not enough evidence yet.”</p><h3>Check whether the skills help</h3><p>The faster test run came from code changes. It does not prove that our new skills will improve every future task.</p><p>We still need to try the skills on real examples. Can an agent improve a debounce test and keep the early-deadline check? Can it test a late result? Can it leave a useful persistence test alone while identifying a weak equality test?</p><p>We should compare the resulting changes and test results. Good-looking instructions alone are not enough. <a href="https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices">Anthropic’s skill guidance</a> recommends testing representative tasks and keeping instructions focused on observed gaps.</p><p>For a first review in another project, I would start with one slow file. Read what it protects, measure it, and check one realistic failure. Then write down the lesson that another developer or agent could use next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4392165d7b4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Organise Years of Saved Instagram Posts and Reels into Folders]]></title>
            <link>https://medium.com/@m1nori/how-to-organise-years-of-saved-instagram-posts-and-reels-into-folders-7e583785017e?source=rss-943a64474b36------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e583785017e</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Valentyna Polienova]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 09:51:01 GMT</pubDate>
            <atom:updated>2026-10-21T09:51:01.862Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An easy guide for Mac users. You will copy a few commands, review a spreadsheet, and choose how to organise your saves.</em></p><p>After years of saving posts, finding one recipe or travel idea can take a long time. Everything is there, but it is mixed together.</p><p>This guide helps you put your saved posts into folders inside Instagram. Instagram calls these folders <strong>collections</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*LHBgWJ7CWkx6C1uygadoVg.png" /><figcaption>My result</figcaption></figure><p>You do not need to write code. You will use a ready-made tool, with two choices:</p><ul><li>Keep your newest saved posts at the top.</li><li>Add posts faster, without keeping a fixed order.</li></ul><p>The tool is available on <a href="https://github.com/valentynapolienova/instagram-organiser">GitHub: Instagram organiser</a>.</p><blockquote><strong><em>Before you start:</em></strong><em> This is an unofficial tool. Instagram may stop its requests, ask you to confirm your identity, or restrict your account. No script can promise that your account will avoid these problems. If you do not want this extra risk, organise your saves manually in the Instagram app. You can read more in the </em><a href="https://github.com/subzeroid/instagrapi/blob/master/docs/usage-guide/best-practices.md"><em>instagrapi guidance</em></a><em>.</em></blockquote><p><strong>1. Download the tool</strong></p><p>Open the <a href="https://github.com/valentynapolienova/instagram-organiser">GitHub project</a>. Click <strong>Code</strong>, then <strong>Download ZIP</strong>.</p><p>Open the ZIP file and keep the unpacked folder in Downloads. Leave its name as instagram-organiser-main.</p><p>You also need Python 3.10 or newer. If you do not have it, install it from the <a href="https://www.python.org/downloads/">official Python website</a>.</p><p>Now open Terminal. On a Mac, press Command + Space, type “Terminal”, and press Enter.</p><p>Copy these commands into Terminal, one line at a time:</p><pre>cd ~/Downloads/instagram-organiser-main<br>python3 -m venv .venv<br>.venv/bin/python -m pip install -r requirements.txt</pre><p>These commands open the project folder and install what the tool needs. Keep this Terminal window open for the next steps.</p><p><strong>2. Connect your Instagram account</strong></p><p>Start by reading just ten saved posts:</p><pre>.venv/bin/python ordered.py export --batch trial --amount 10</pre><p>This small test does not change your saves.</p><p>Enter your Instagram username and password when asked. Your password will stay invisible while you type. That is normal.</p><p>Instagram may also ask for a two-factor authentication code, usually called a <strong>2FA code</strong>.</p><p>If you use an authenticator app, open it and use the current Instagram code.</p><p>There is one detail that can be confusing: <strong>the code prompt does not mean Instagram sent a WhatsApp or SMS message.</strong></p><p>If no message arrives, do not keep requesting codes or guessing them. You can use an unused eight-digit Instagram backup code instead, if you have one. Look for backup codes in your Instagram two-factor authentication settings. Instagrapi <a href="https://github.com/subzeroid/instagrapi#readme">supports these codes</a>.</p><p>Enter passwords and codes only in Terminal. Never share them in screenshots or upload them to GitHub.</p><p>If you cannot complete the login, press Ctrl+C to stop. Check the official Instagram app before trying again. Keep 2FA turned on.</p><p>After a successful login, the tool saves a local session. Later commands can reuse it without starting a new password login.</p><p><strong>3. Turn your saves into a spreadsheet</strong></p><p>Once the small test works, export your full library:</p><pre>.venv/bin/python ordered.py export --batch library --amount 0</pre><p>Here, 0 means all saved posts that Instagram returns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYoH5FsmTycNrxDy-9pjHg.png" /><figcaption>Console output</figcaption></figure><p>This step only reads your saves. It creates a list with captions and links; it does not download the photos or videos. Deleted or unavailable posts may be missing.</p><p>When it finishes, open the project folder in Finder. Go to:</p><pre>private-data → library → review.csv</pre><p>Open review.csv in Numbers or Excel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ktYgL8cP1C8muCrwfN0fWQ.png" /><figcaption>My proposal</figcaption></figure><p>I also used this API + AI to remove non-vegetarian recipes from my saves :)</p><p>Now you can review your saves on a larger screen, instead of scrolling through them on your phone.</p><p><strong>4. Choose your collections</strong></p><p>Instagram calls its saved-post folders <strong>collections</strong>.</p><p>Create the collections you want in the Instagram app first. You might choose Recipes, Clothes, Beauty, Places, or Home Ideas.</p><p>Then return to the spreadsheet. Edit only the columns named action and collection.</p><p>For each post, you have three choices:</p><ul><li>Write keep and leave the collection empty to preserve its saved status and current collections.</li><li>Write add and enter a collection name, such as Recipes.</li><li>Write unsave and leave the collection empty to remove it from Saved entirely.</li></ul><p>Every row starts as keep, so you can organise a small group first.</p><p>Collection names must match the names in Instagram exactly. Keep the item IDs and column names unchanged.</p><p>When finished, save or export the file as <strong>UTF-8 CSV</strong>, replacing the original review.csv. Saving only an Excel or Numbers workbook will not update the file the tool reads.</p><p>Be careful with unsave: it removes a post from Saved, including its collections. If you are unsure, leave it as keep.</p><p>The tool does not choose categories or understand every recipe for you. Its ingredient hints can be wrong. Open unclear posts before deciding to remove them.</p><p><strong>5. Choose between order and speed</strong></p><p>This is the main choice.</p><p>The <strong>ordered version</strong> puts your most recently saved posts first. It follows when you saved a post, rather than its publication date.</p><p>To get that order, it adds or moves posts one at a time. It skips collections that are already correct.</p><p>The <strong>unordered version</strong> adds missing posts in groups of up to 30. This usually takes less time because it sends fewer requests to Instagram.</p><p>For example, adding 300 new posts to an empty collection needs about 10 write requests in the faster version. The ordered version needs 300 individual additions. Both also make requests to check the results.</p><p>Both versions wait between requests. The faster version saves time through fewer requests, but Instagram may mix the order of posts within each group.</p><p>Choose the ordered version if you care about seeing your newest saves first. Choose the unordered version if getting posts into the right folders matters more than their position.</p><blockquote><em>To give you an idea of the time, we started with 1,001 saved posts. After reviewing and removing unwanted saves, we added 844 posts to 15 collections. The successful batch run took about </em><strong><em>7–8 minutes</em></strong><em>. Later, putting around 840 collection entries into newest-saved-first order took about </em><strong><em>1 hour and 30 minutes</em></strong><em>. Exact ordering needed hundreds of separate requests, while batching handled up to 30 posts at once. These times cover the script’s work, not installation or reviewing the spreadsheet. Your results may differ.</em></blockquote><p><strong>6. Preview your choices, then apply them</strong></p><p>First, run a preview. It reads your local review file without contacting Instagram.</p><p>For the ordered version:</p><pre>.venv/bin/python ordered.py apply --batch library</pre><p>When your review is ready, apply it:</p><pre>.venv/bin/python ordered.py apply --batch library --execute</pre><p>For the faster version, use unordered.py in those same two commands instead.</p><p>Choose one version before starting. Do not switch versions after changes begin.</p><p>The ordered version also sorts existing posts in each collection you add to. Their positions may change, but their collection memberships stay the same. It needs the original saved order for every post in those collections. If your export is missing a post, it stops before writing.</p><p>If your review includes removals, the apply command also needs --allow-unsave. For example:</p><pre>.venv/bin/python ordered.py apply --batch library --execute --allow-unsave</pre><p>Keep your Mac awake while the tool works. Run only one copy, and avoid editing the same collections in Instagram during the run.</p><p>The tool checks each collection after updating it. The ordered version checks both the posts and their order.</p><p><strong>If something stops, do not keep retrying</strong></p><p>Open the official Instagram app if you see an account warning or a request to confirm your identity.</p><p>The tool saves its progress. Sometimes it cannot tell whether Instagram completed a request, so it stops to avoid repeating the change.</p><p>Do not delete its progress files to force another attempt. Follow the recovery steps in the <a href="https://github.com/valentynapolienova/instagram-organiser/blob/main/GUIDE.md">full project guide</a>.</p><p>That guide also explains how to sort collections you already have, without adding or removing posts.</p><p><strong>Log out when you are finished</strong></p><p>When you have finished using the tool, run:</p><pre>.venv/bin/python ordered.py logout --execute</pre><p>If Instagram confirms logout, the tool removes its local session file. Your exported list and review stay on your computer.</p><p>A future run will need a new login. Logging out does not remove account limits.</p><p>Keep the entire private-data folder private. It contains your saved-post information and may contain a login session while the tool is in use. Never upload that folder to GitHub or share it with someone else.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e583785017e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build an AI Telegram Chat Summarizer Bot with Python and OpenAI (Step-by-Step Guide)]]></title>
            <link>https://medium.com/@m1nori/how-to-build-an-ai-telegram-chat-summarizer-bot-with-python-and-openai-step-by-step-guide-b6d3cad43bf4?source=rss-943a64474b36------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6d3cad43bf4</guid>
            <category><![CDATA[ai-projects]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Valentyna Polienova]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 21:27:29 GMT</pubDate>
            <atom:updated>2026-10-19T21:27:29.972Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Learn how to create a Telegram bot that summarizes group chats, understands voice messages and video notes, and runs 24/7.</em></p><p>I have a group chat with my girlfriends and honestly I don’t really like to spend much time in messangers :) One day I decided that I’m tired to open a Telegram group chat and find hundreds of unread messages!</p><p>I wanted a simple solution: a bot that could read our conversation and explain <strong>who said what, what we discussed, and what conclusions we reached</strong>.</p><p>So I built one using Python, OpenAI, and Telegram Bot API. Here is how it looks :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9n131GoiR4eSkHlYYTivg.png" /></figure><p>The best part? It costs me around $5/month for hosting, plus occasional OpenAI API credits.</p><p>In this guide, I’ll explain how to create your own bot, even if you’ve never built one before.</p><h3>Step 1: Create Your Telegram Bot</h3><p>First, open Telegram and find <a href="https://t.me/BotFather">@BotFather</a>.</p><p>Send this command:</p><pre>/newbot</pre><p>BotFather will ask you to choose a name and username. After that, you’ll receive a <strong>Telegram Bot Token</strong>.</p><p>Save it somewhere safe. You’ll need it later.</p><p>Next, allow your bot to read group messages:</p><ol><li>Open BotFather and send /mybots.</li><li>Select your bot.</li><li>Go to <strong>Bot Settings → Group Privacy</strong>.</li><li>Turn Privacy Mode <strong>OFF</strong>.</li></ol><p>Now add your bot to your Telegram group.</p><p><strong>Important:</strong> Telegram bots cannot read old messages. Your bot will only collect messages received after it joins the group.</p><h3>Step 2: Set Up Your Python Project</h3><p>We’ll use Python 3.12.</p><p>Create a new folder with this structure:</p><pre>telegram-summary-bot/<br>├── bot.py<br>├── requirements.txt<br>├── Dockerfile<br>├── .env<br>└── .gitignore</pre><p>Open your terminal and create a virtual environment:</p><pre>python3.12 -m venv .venv<br>source .venv/bin/activate</pre><p>Add these libraries to requirements.txt:</p><pre>python-telegram-bot==20.7<br>openai<br>aiosqlite<br>python-dotenv</pre><p>Install them:</p><pre>python3 -m pip install -r requirements.txt</pre><p>We’ll use:</p><ul><li><strong>python-telegram-bot</strong> to communicate with Telegram.</li><li><strong>OpenAI</strong> to summarize messages and transcribe speech.</li><li><strong>aiosqlite</strong> to store chat messages.</li><li><strong>python-dotenv</strong> to manage API keys.</li></ul><h3>Step 3: Connect OpenAI</h3><p>Create an API key at <a href="https://platform.openai.com/">OpenAI Platform</a>.</p><p>Then add your credentials to .env:</p><pre>TELEGRAM_BOT_TOKEN=your_telegram_token<br>OPENAI_API_KEY=your_openai_api_key</pre><p>Load them in bot.py:</p><pre>import os<br>from dotenv import load_dotenv<br>from openai import OpenAI<br><br>load_dotenv()<br><br>TELEGRAM_BOT_TOKEN = os.getenv(&quot;TELEGRAM_BOT_TOKEN&quot;)<br>OPENAI_API_KEY = os.getenv(&quot;OPENAI_API_KEY&quot;)<br><br>client = OpenAI(api_key=OPENAI_API_KEY)Never upload your .env file to GitHub.</pre><p>Never upload your .env file to GitHub.</p><p>OpenAI API usage is paid separately from ChatGPT subscriptions.</p><h3>Step 4: Save Telegram Messages</h3><p>Our bot needs to remember messages before it can summarize them.</p><p>For this, I used <strong>SQLite</strong>, a simple database that doesn’t need a separate server.</p><p>Each saved message contains:</p><ul><li>Chat ID</li><li>Message ID</li><li>Username</li><li>Message text</li><li>Timestamp</li></ul><p>We use a Telegram message handler to receive new messages:</p><pre>app.add_handler(<br>    MessageHandler(<br>        filters.TEXT &amp; ~filters.COMMAND,<br>        store_message<br>    )<br>)</pre><p>The store_message() function saves each message to SQLite.</p><p>I also added automatic database cleanup, so old messages don’t stay there forever.</p><p>The bot only needs a few hundred recent messages because the maximum summary length is <strong>150 messages</strong>.</p><h3>Step 5: Generate AI Summaries</h3><p>Now comes the interesting part!</p><p>When someone types:</p><pre>/summary 100</pre><p>The bot gets the last 100 saved messages and sends them to OpenAI.</p><p>I used gpt-4.1-mini:</p><pre>response = client.chat.completions.create(<br>    model=&quot;gpt-4.1-mini&quot;,<br>    messages=[<br>        {<br>            &quot;role&quot;: &quot;system&quot;,<br>            &quot;content&quot;: &quot;You summarize Telegram conversations.&quot;<br>        },<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: prompt<br>        }<br>    ],<br>    temperature=0.2<br>)<br><br>summary = response.choices[0].message.contentMy summary has four sections:</pre><p>The prompt contains the conversation and instructions for the AI.</p><p>My summary has four sections:</p><ol><li><strong>Who said what:</strong> Main topics, opinions, and ideas from each participant.</li></ol><p><strong>2. Conclusions:</strong> Decisions and agreements.</p><p><strong>3. Open questions:</strong> Things that are still unclear.</p><p><strong>4. Wisdom of the day:</strong> A short lesson or funny insight from the conversation.</p><p>While OpenAI processes the messages, the bot shows:</p><blockquote><em>⏳ Analyzing the last 100 messages…</em></blockquote><p>When the summary is ready, the bot removes this message and sends the result.</p><p>Users can choose how many messages to analyze:</p><pre>/summary 50<br>/summary 100<br>/summary 150</pre><h3>Step 6: Add Voice Message Support</h3><p>Text summaries are useful, but our group also sends many voice messages.</p><p>I wanted the bot to understand them too.</p><p>Telegram has two message types we need:</p><pre>filters.VOICE       # Voice messages<br>filters.VIDEO_NOTE  # Round video messages</pre><p>When someone sends a voice message, the bot downloads it and uses <strong>OpenAI Whisper</strong> to convert speech into text:</p><pre>with open(audio_path, &quot;rb&quot;) as audio:<br>    transcript = client.audio.transcriptions.create(<br>        model=&quot;whisper-1&quot;,<br>        file=audio<br>    )<br><br>text = transcript.text</pre><p>Then it saves the transcription to SQLite, just like a normal text message.</p><h3>What About Telegram Video Circles?</h3><p>Video circles are slightly different.</p><p>First, we need to extract audio using <strong>FFmpeg</strong>:</p><pre>ffmpeg -i video.mp4 -vn audio.mp3</pre><p>Then we send the audio to Whisper.</p><p>The complete process:</p><pre>Telegram message<br>       ↓<br>Text / Voice / Video circle<br>       ↓<br>Speech-to-text (if needed)<br>       ↓<br>SQLite database<br>       ↓<br>OpenAI GPT<br>       ↓<br>Telegram summary</pre><p>The bot doesn’t analyze what is happening visually in the video. It only understands the speech.</p><h3>Step 7: Deploy the Bot to Railway</h3><p>The bot is now ready, but there’s one problem.</p><p>If you run it on your computer, it stops when your computer is turned off.</p><p>I used <a href="https://railway.app/">Railway</a> to keep it running 24/7.</p><h3>1. Push Your Code to GitHub</h3><p>Create a private repository and upload your project.</p><p>Add a .gitignore file:</p><pre>.venv/<br>.env<br>*.db<br>__pycache__/</pre><h3>2. Create a Railway Project</h3><p>Open Railway and select:</p><p><strong>New Project → Deploy from GitHub Repo</strong></p><p>Choose your repository.</p><h3>3. Add Environment Variables</h3><p>Open the <strong>Variables</strong> tab and add:</p><pre>TELEGRAM_BOT_TOKEN<br>OPENAI_API_KEY</pre><p>Make sure the variables are connected to your Railway service.</p><h3>4. Create a Dockerfile</h3><p>We need FFmpeg to process video circles.</p><p>Create a file called Dockerfile (without any extension):</p><pre>FROM python:3.12-slim<br><br>RUN apt-get update \<br>    &amp;&amp; apt-get install -y --no-install-recommends ffmpeg ca-certificates \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br>WORKDIR /app<br><br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br><br>COPY . .<br><br>CMD [&quot;python&quot;, &quot;bot.py&quot;]RUN apt-get update \<br>    &amp;&amp; apt-get install -y --no-install-recommends ffmpeg ca-certificates \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><p>Railway will use this file to build the application with Python and FFmpeg.</p><h3>5. Configure Persistent Storage</h3><p>Railway containers don’t guarantee permanent local storage.</p><p>To keep your SQLite database after deployments, attach a Railway Volume mounted at /data.</p><p>Update your database path:</p><pre>DB_PATH = os.getenv(&quot;DB_PATH&quot;, &quot;messages.db&quot;)</pre><p>Then add this Railway variable:</p><pre>DB_PATH=/data/messages.db</pre><h3>6. Deploy!</h3><p>Push your changes to GitHub.</p><p>Railway will build and start your bot.</p><p>One important detail: <strong>don’t run the same bot locally and on Railway at the same time</strong>. Telegram allows only one active polling instance per bot token.</p><h3>Step 8: Test Your Bot</h3><p>Open your Telegram group and send:</p><pre>/start</pre><p>Next, send a few normal text messages and try:</p><pre>/summary 20</pre><p>You should receive an AI-generated summary.</p><p>Now test a voice message and a video circle. Wait until the transcription finishes, then request another summary.</p><p>If everything works, your bot is ready!</p><h3>💰 How Much Does It Cost?</h3><p>The bot is surprisingly cheap to run!</p><p>Here’s what I currently pay:</p><ul><li><strong>Railway hosting:</strong> $5/month to keep the bot running 24/7.</li><li><strong>OpenAI API:</strong> Around $10 every few months. Depending on usage, this can last up to 6 months!</li></ul><p>OpenAI uses a pay-as-you-go model, so you only pay for the AI requests you make. Of course, costs may be higher for larger or more active groups.</p><h3>Final Thoughts</h3><p>You now have an AI Telegram bot that can:</p><ul><li>Save group messages in SQLite.</li><li>Analyze up to 150 recent messages.</li><li>Create structured AI summaries.</li><li>Understand voice messages and video circles.</li><li>Run 24/7 using Railway.</li></ul><p>The project uses only Python, Telegram Bot API, OpenAI, and a small database.</p><p><strong>One final note:</strong> Because the bot processes private conversations, make sure everyone in your group agrees to this. Chat text and transcribed speech are sent to OpenAI for analysis.</p><p>That’s it! You have your own AI-powered Telegram chat summarizer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6d3cad43bf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Architecture in Flutter]]></title>
            <link>https://medium.com/@m1nori/clean-architecture-in-flutter-b00aa22ffad3?source=rss-943a64474b36------2</link>
            <guid isPermaLink="false">https://medium.com/p/b00aa22ffad3</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-architecture]]></category>
            <dc:creator><![CDATA[Valentyna Polienova]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 19:08:35 GMT</pubDate>
            <atom:updated>2026-10-20T15:02:53.834Z</atom:updated>
            <content:encoded><![CDATA[<h4>What it is, why teams use it, and when you shouldn’t. Explained with one small, real app you can clone and run.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZi1cO9TfyUlgD50hsqMuA.png" /></figure><p>If you’ve built a couple of Flutter apps, you’ve probably written this screen: it calls the API, parses the JSON, decides what to show, catches errors and rebuilds itself. It works. Then the app grows, and every change starts to hurt.</p><p><strong>Clean architecture is a set of habits that keeps that pain away.</strong> This article explains it from zero: the problem, the idea, and real code from an <a href="https://github.com/valentynapolienova/flutter_clean_architecture_template">open-source Flutter template</a> you can run in five minutes.</p><p>By the end you’ll know:</p><ul><li>what problem clean architecture solves,</li><li>the four layers and what goes into each,</li><li>how a single tap travels through the app,</li><li>how it compares to other approaches,</li><li>and when it’s the right tool, and when it’s overkill.</li></ul><h3>The problem: one widget that does everything</h3><p>Here’s a screen that shows a blog post and its author. Most of us have written something like it.</p><p><strong>post_screen.dart</strong> <em>· everything in one place</em></p><pre>class _PostScreenState extends State&lt;PostScreen&gt; {<br><br>  Map&lt;String, dynamic&gt;? post;<br>  String? authorName;<br>  String? error;<br>  bool loading = true;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    load ();<br>  }<br><br>  Future&lt;void&gt; load() async {<br>    try {<br>      final token = await const FlutterSecureStorage().read(key: &#39;token&#39;);<br>      final dio = Dio(BaseOptions(baseUrl: &#39;https://dummyjson.com&#39;));<br>      final options = Options(headers: {&#39;Authorization&#39;: &#39;Bearer $token&#39;});<br>      final postRes = await dio.get(&#39;/auth/posts/${widget.postId}&#39;, options: options);<br>      final userId = postRes.data[&#39;userId&#39;];<br>      final userRes = await dio.get(&#39;/auth/users/$userId&#39;, options: options);<br>      setState(() {<br>        post = postRes.data;<br>        authorName = &#39;${userRes.data[&#39;firstName&#39;]} ${userRes.data[&#39;lastName&#39;]}&#39;;<br>        loading = false;<br>      });<br>    } catch (e) {<br>      setState(() {<br>        error = &#39;Something went wrong&#39;;<br>        loading = false;<br>      });<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    if (loading) return const Center(child: CircularProgressIndicator());<br>    if (error != null) return Center(child: Text(error!));<br>    return Column(<br>      children: [<br>        Text(post![&#39;title&#39;]),<br>        Text(&#39;Written by $authorName&#39;),<br>        Text(post![&#39;body&#39;]),<br>      ],<br>    );<br>  }<br>}</pre><p>Nothing here is <em>wrong</em>. But count how many jobs this one class has. It knows:</p><ul><li>where the login token is stored,</li><li>the server’s address and its URL paths,</li><li>the exact shape of the JSON (userId, firstName),</li><li>a business rule: “a post screen needs its author”,</li><li>how to show loading and errors,</li><li>and how to draw the screen.</li></ul><p>Now picture a normal week on a real project:</p><ul><li><strong>The backend renames</strong> userId <strong>to</strong> authorId. You edit a screen. Then you find four more screens that parse the same JSON.</li><li><strong>A second screen also needs “post plus author”.</strong> You copy twenty lines, and now the rule lives in two places.</li><li><strong>Your lead asks for a test of “load the post, then its author”.</strong> You need a widget test, a fake Dio and a fake secure storage, all for one small rule.</li><li><strong>A user opens the app in the metro.</strong> They see “Something went wrong”, the same message as a server crash, so they have no idea what to do.</li></ul><p><strong>The code isn’t broken, it’s tangled.</strong> Every change touches everything, so every change is risky.</p><h3>The idea in one sentence</h3><blockquote><strong><em>Give every piece of code one job, and let each job depend on as few others as possible.</em></strong></blockquote><p>Think of a restaurant.</p><ul><li><strong>The waiter</strong> takes your order and brings the plate. The waiter doesn’t cook.</li><li><strong>The chef</strong> decides how the dish is made: which ingredients, in which order, following the house rules.</li><li><strong>The storeroom</strong> gets ingredients from wherever they come from: the fridge, the market, a delivery van.</li><li><strong>The menu </strong>describes the dishes in words that everyone in the restaurant understands.</li></ul><p>If the restaurant switches suppliers, the waiter doesn’t notice. If the waiter changes, the recipes stay the same. That’s the whole idea. Clean architecture simply gives these roles names in code.</p><h3>The four layers</h3><p>In the template, each feature of the app (posts, login, settings…) is split into four layers. Here’s how they relate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_mkq0DUMm28y7LVCNkgrA.png" /></figure><p>In restaurant terms: presentation is the waiter, application is the chef, data is the storeroom and domain is the menu. Let’s rebuild the post screen layer by layer, starting from the bottom.</p><h3>Domain — The words of your app</h3><p>Domain models describe the things your app is about. They’re plain Dart classes.</p><p><strong>features/posts/domain/post.dart</strong></p><pre>class Post extends Equatable {<br>  const Post({<br>    required this.id,<br>    required this.authorId,<br>    required this.title,<br>    required this.body,<br>  });<br><br>  final int id;<br>  final int authorId;<br>  final String title;<br>  final String body;<br>  @override<br>  List&lt;Object?&gt; get props =&gt; [id, authorId, title, body];<br>}</pre><p>No Flutter import. No JSON. No Dio. If you printed this file and handed it to a product manager, they’d understand it. (Equatable just makes two posts with the same fields equal to each other, which tests love.)</p><h3>Data — Where information comes from</h3><p>The data layer has two kinds of classes. A DTO (data transfer object) looks exactly like the API response:</p><p><strong>features/posts/data/dto/post_dto.dart</strong></p><pre>class PostDto {<br>  const PostDto({<br>    required this.id,<br>    required this.userId,<br>    required this.title,<br>    required this.body,<br>  });<br><br>factory PostDto.fromJson(Map&lt;String, dynamic&gt; json) {<br>    return PostDto(<br>      id: json[&#39;id&#39;] as int,<br>      userId: json[&#39;userId&#39;] as int,<br>      title: json[&#39;title&#39;] as String,<br>      body: json[&#39;body&#39;] as String,<br>    );<br>  }<br><br>  final int id;<br>  final int userId;<br>  final String title;<br>  final String body;<br><br>  Post toDomain() =&gt; Post(id: id, authorId: userId, title: title, body: body);<br>}</pre><p>Notice the last line. The API calls it userId, but the app calls it authorId. toDomain() <strong>is the only place in the whole app where both names meet</strong>. When the backend renames the field, you change one line and no screen notices.</p><p>A <strong>repository</strong> fetches the data and hands back domain models:</p><p><strong>features/posts/data/posts_repository.dart</strong></p><pre>class PostsRepository {<br>  const PostsRepository({required this.api});<br><br>  final ApiClient api;<br><br>  Future&lt;Post&gt; fetchPost(int postId) async {<br>    final json = await api.getJson(&#39;/auth/posts/$postId&#39;);<br>    return PostDto.fromJson(json).toDomain();<br>  }<br>}</pre><p>ApiClient is a thin wrapper around Dio from the template. It adds the login token to every request and turns network problems into clear error types. We&#39;ll get to those in a minute.</p><h3>Application — The rules</h3><p>“A post screen needs its author” is a rule. Rules live in a service:</p><p><strong>features/posts/application/posts_service.dart</strong></p><pre>class PostsService {<br>  const PostsService({<br>    required this.postsRepository,<br>    required this.authorsRepository,<br>  });<br><br>  final PostsRepository postsRepository;<br>  final AuthorsRepository authorsRepository;<br><br>  FutureFailable&lt;PostDetails&gt; getPostDetails(int postId) {<br>    return RepositoryRequestHandler&lt;PostDetails&gt;()(<br>      request: () async {<br>        final post = await postsRepository.fetchPost(postId);<br>        final author = await authorsRepository.fetchAuthor(post.authorId);<br>        return PostDetails(post: post, author: author);<br>      },<br>    );<br>  }<br>}</pre><p>Two new names here:</p><ul><li><strong>FutureFailable&lt;T&gt;</strong> is a future that holds either Succeeded(value) or Failed(failure). The caller <em>has</em> to handle both.</li><li><strong>RepositoryRequestHandler</strong> runs the code and catches any error, so nothing above this layer ever needs a try/catch.</li></ul><p>Now any screen that needs “post plus author” calls one method, and the rule lives in exactly one place.</p><h3>Presentation — The screen</h3><p>The screen is split in two. A <strong>Cubit</strong> (from the flutter_bloc package) holds the screen&#39;s state, and a <strong>page</strong> draws it. First, the possible states:</p><p><strong>post_details_state.dart </strong><em>(simplified)</em></p><pre>sealed class PostDetailsState {}<br><br>class PostDetailsLoading extends PostDetailsState {}<br><br>class PostDetailsLoaded extends PostDetailsState {<br>  PostDetailsLoaded(this.details);<br>  final PostDetails details;<br>}<br><br>class PostDetailsFailed extends PostDetailsState {<br>  PostDetailsFailed(this.failure);<br>  final AppFailure failure;<br>}</pre><p>The Cubit asks the service and turns the answer into a state:</p><p><strong>post_details_cubit.dart</strong> <em>(simplified)</em></p><pre>class PostDetailsCubit extends Cubit&lt;PostDetailsState&gt; {<br>  PostDetailsCubit(this._service) : super(PostDetailsLoading());<br><br>  final PostsService _service;<br><br>  Future&lt;void&gt; load(int postId) async {<br>    emit(PostDetailsLoading());<br>    final result = await _service.getPostDetails(postId);<br>    emit(<br>      result.when&lt;PostDetailsState&gt;(<br>        success: (details) =&gt; PostDetailsLoaded(details),<br>        failure: (failure) =&gt; PostDetailsFailed(failure),<br>      ),<br>    );<br>  }<br>}</pre><p>And the page only draws whatever state it’s given:</p><p><strong>post_details_page.dart</strong></p><pre>BlocBuilder&lt;PostDetailsCubit, PostDetailsState&gt;(<br>  builder: (context, state) =&gt; switch (state) {<br>    PostDetailsLoading() =&gt; const Center(child: CircularProgressIndicator()),<br>    PostDetailsFailed(:final failure) =&gt; ErrorView(<br>      failure: failure,<br>      onRetry: () =&gt; context.read&lt;PostDetailsCubit&gt;().load(postId),<br>    ),<br>    PostDetailsLoaded(:final details) =&gt; PostContent(details: details),<br>  },<br>)</pre><p>Because the state class is sealed, <strong>the compiler checks that you handled every case</strong>. Forget the error state and the app doesn&#39;t compile. That&#39;s much better than finding out from a crash report.</p><p>Let’s be honest about the cost. The 60-line widget became five small files. That’s more files, but each one does one thing and takes about thirty seconds to read.</p><h3>The rule that makes it work: dependencies point one way</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_iwQ9jPpGZL5I6ew0n8GA.png" /></figure><p>Read the arrows as “knows about”:</p><ul><li>Screens know about services. <strong>Services never know about screens.</strong></li><li>Services know about repositories. <strong>Repositories never know about services.</strong></li><li>Everyone can use domain models. <strong>Domain models know about nobody.</strong></li></ul><p>Here’s a simple way to remember why this matters: <strong>a change can only break the code that points at it.</strong></p><ul><li>Switch from REST to GraphQL? Only the data layer changes.</li><li>Redesign the post screen? Only the presentation layer changes.</li><li>Change the rule about authors? Only the service changes, and the screens get the new behaviour for free.</li></ul><h3>Follow one tap through the app</h3><p>Here’s what happens, in order, when a user taps a post in the template app:</p><ol><li>The router opens /posts/42 and creates a fresh PostDetailsCubit.</li><li>The Cubit emits PostDetailsLoading, and the page shows a spinner.</li><li>The Cubit calls PostsService.getPostDetails(42).</li><li>The service asks PostsRepository for the post, then AuthorsRepository for its author.</li><li>Each repository gets JSON from ApiClient and turns it into a Post or an Author through its DTO.</li><li>The service combines them into PostDetails and returns Succeeded(details).</li><li>The Cubit emits PostDetailsLoaded, and the page draws the post.</li></ol><p>And if the phone is offline at step 5? ApiClient throws a NoConnectionFailure. The service returns Failed(NoConnectionFailure()), the Cubit emits PostDetailsFailed, and the page says <em>&quot;No internet connection. Check your network and try again.&quot;</em> with a Retry button. Not a single try/catch was written in the screen.</p><h3>Errors, handled once</h3><p>Remember “Something went wrong”? The template replaces it with a small, closed list of things that can actually go wrong:</p><p><strong>core/errors/app_failure.dart</strong> <em>(shortened)</em></p><pre>sealed class AppFailure implements Exception {<br>  const AppFailure();<br>}<br><br>final class NoConnectionFailure extends AppFailure {<br>  const NoConnectionFailure();<br>}<br><br>final class TimeoutFailure extends AppFailure {<br>  const TimeoutFailure();<br>}<br><br>final class ServerFailure extends AppFailure {<br>  const ServerFailure({this.statusCode});<br>  final int? statusCode;<br>}<br><br>final class UnauthorizedFailure extends AppFailure {<br>  const UnauthorizedFailure();<br>}</pre><p>Then one function turns each failure into a message in the user’s language:</p><p><strong>core/extensions/failure_message.dart</strong> <em>(shortened)</em></p><pre>extension FailureMessage on AppFailure {<br>  String toMessage(AppLocalizations l10n) =&gt; switch (this) {<br>    NoConnectionFailure() =&gt; l10n.errorNoConnection,<br>    TimeoutFailure() =&gt; l10n.errorTimeout,<br>    ServerFailure() =&gt; l10n.errorServer,<br>    UnauthorizedFailure() =&gt; l10n.errorSessionExpired,<br>  };<br>}</pre><p>Two good things happen:</p><ul><li><strong>Users get useful messages.</strong> Offline users are told they’re offline; they don’t see the same text as a server crash.</li><li><strong>The compiler has your back.</strong> Add a new failure type, and every switch that doesn&#39;t handle it becomes a compile error.</li></ul><h3>Folder structure: organize by feature</h3><p>There are two popular ways to arrange the folders. <strong>Layer-first </strong>groups files by what they are. <strong>Feature-first</strong> groups them by what they’re for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SHR4fVe9cuqQ93CGCbCJZg.png" /></figure><p>The template uses feature-first, because:</p><ul><li><strong>Working on “posts” means opening one folder</strong>, not four.</li><li><strong>Removing a feature means deleting one folder.</strong></li><li><strong>Teammates rarely edit the same files</strong>, so you get fewer merge conflicts.</li></ul><p>Here’s the full layout of the template:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lp2AQMnTu6n14kGY-45few.png" /></figure><p>core/ is for code that several features share. <strong>A good habit:</strong> write code inside the feature first, and move it to core/ only when a second feature needs it.</p><h3>Testing gets boring (in a good way)</h3><p>Every class receives what it needs through its constructor. That means that in a test you can hand it fakes instead of the real thing. Here’s the “post plus author” rule, tested without a single widget or network call:</p><p><strong>test/features/posts/application/posts_service_test.dart</strong></p><pre>test(&#39;getPostDetails combines the post with its author&#39;, () async {<br>  final postsRepository = MockPostsRepository();<br>  final authorsRepository = MockAuthorsRepository();<br>  final service = PostsService(<br>    postsRepository: postsRepository,<br>    authorsRepository: authorsRepository,<br>  );<br><br>  when(() =&gt; postsRepository.fetchPost(1)).thenAnswer((_) async =&gt; testPost);<br>  when(() =&gt; authorsRepository.fetchAuthor(testPost.authorId))<br>      .thenAnswer((_) async =&gt; testAuthor);<br>  final result = await service.getPostDetails(1);<br>  expect(<br>    result,<br>    const Succeeded(PostDetails(post: testPost, author: testAuthor)),<br>  );<br>});</pre><p>It runs in milliseconds. Cubits are just as easy with bloc_test: you describe an action and list the states you expect.</p><p><strong>test/features/auth/presentation/cubits/login_cubit_test.dart</strong></p><pre>blocTest&lt;LoginCubit, LoginState&gt;(<br>  &#39;shows why signing in failed&#39;,<br>  setUp: () =&gt; when(<br>    () =&gt; authService.signIn(username: &#39;emilys&#39;, password: &#39;wrong&#39;),<br>  ).thenAnswer((_) async =&gt; const Failed(InvalidCredentialsFailure())),<br>  build: () =&gt; LoginCubit(authService),<br>  act: (cubit) =&gt; cubit.signIn(username: &#39;emilys&#39;, password: &#39;wrong&#39;),<br>  expect: () =&gt; const [<br>    LoginInProgress(),<br>    LoginFailed(InvalidCredentialsFailure()),<br>  ],<br>);</pre><p>What to test in each layer:</p><ul><li><strong>Repositories</strong>: fake the API client and check that JSON becomes the right models.</li><li><strong>Services</strong>: fake the repositories and check the rules and the success or failure result.</li><li><strong>Cubits</strong>: fake the services and check the exact list of states.</li><li><strong>Pages</strong>: fake the Cubit and check what’s drawn for each state.</li></ul><h3>How it compares</h3><h4>Everything in widgets</h4><p>This is the screen from the start of the article: StatefulWidget, setState and direct API calls.</p><ul><li><strong>Good for</strong>: learning Flutter, tiny apps, prototypes.</li><li><strong>Hurts when</strong>: the app grows, a second developer joins, or you need tests.</li></ul><h4>MVVM, or “just Cubits”</h4><p>Each screen gets a ViewModel or Cubit, and that class calls the API directly.</p><ul><li><strong>Good for</strong>: small and medium apps. It’s already a big step up.</li><li><strong>Hurts when</strong>: Cubits grow into 500-line classes that mix HTTP, JSON, rules and UI state.</li></ul><p>Clean architecture doesn’t replace MVVM. <strong>Your Cubit basically <em>is</em> the ViewModel.</strong> Clean architecture adds two floors underneath it, services and repositories, so the Cubit stays small.</p><h4>Textbook clean architecture</h4><p>This is the strict version you’ll find in many tutorials: a use case class for every action, an interface plus an implementation for every repository, and mappers everywhere.</p><ul><li><strong>Good for:</strong> very large codebases with many teams and strict boundaries.</li><li><strong>Hurts when</strong>: you drown in ceremony. GetPostUseCase, GetPostsUseCase, PostRepository, PostRepositoryImpl… for one screen.</li></ul><p><strong>Textbook</strong>: one class per action</p><pre>class GetPostDetailsUseCase {<br>  GetPostDetailsUseCase(this.repo);<br><br>  final PostRepository repo;<br><br>  Future&lt;Either&lt;Failure, PostDetails&gt;&gt;<br>      call(int id) { /* ... */ }<br>  }<br><br> class GetPostsUseCase { /* ... */ }<br><br> class SearchPostsUseCase { /* ... */ }</pre><p><strong>Template</strong>: related actions together</p><pre>class PostsService {<br><br>  FutureFailable&lt;PageSlice&lt;Post&gt;&gt; getPosts({<br>    required int skip,<br>    required int limit,<br>    String query = &#39;&#39;,<br>  }) { /* ... */ }<br><br>  FutureFailable&lt;PostDetails&gt; getPostDetails(int postId) {<br>   /* ... */ <br>  }<br>}</pre><p>The template takes the pragmatic middle road: <strong>add structure only when it pays for itself</strong>. Use an interface when there really are two implementations (like device storage). Split a service when it really gets too big.</p><h4>What about Riverpod or Provider?</h4><p>Architecture is about <em>responsibilities</em>, not packages. Andrea Bizzotto describes the <a href="https://codewithandrea.com/articles/flutter-app-architecture-riverpod-introduction/">same four layers with Riverpod</a>. The template uses Cubit and get_it instead. You can swap the state management package and keep the layers exactly as they are.</p><h3>When to use it, and when not</h3><p><strong>Use it when:</strong></p><ul><li>the app will live longer than a few months,</li><li>more than one developer works on it,</li><li>there are more than a handful of screens,</li><li>data comes from several places (an API, device storage, login),</li><li>you want tests and CI you can trust,</li><li>AI coding assistants write part of the code, since clear conventions keep their output consistent.</li></ul><p><strong>Skip it when:</strong></p><ul><li>it’s a hackathon, a prototype or a throwaway demo,</li><li>the app is a single screen,</li><li>you’re still learning widgets and state (learn those first),</li><li>the code will be deleted next week.</li></ul><p><strong>Not sure? Grow into it.</strong> Start with feature folders and one Cubit per screen. Add a repository the first time you parse JSON. Add a service the first time a rule is needed twice or combines two data sources. Architecture is something a project grows into, not a box you tick on day one.</p><h3>Common mistakes</h3><p><strong>Calling Dio from a Cubit</strong> “just this once”.<br><strong>Instead</strong>: put it in a repository. “Just this once” quietly becomes the pattern.</p><p><strong>Returning a JSON</strong> Map f<strong>rom a repository.<br>Instead:</strong> return domain models. JSON never leaves the DTOs.</p><p><strong>Passing</strong> BuildContext <strong>into a service to show a snackbar.<br>Instead</strong>: return a failure. The page decides how to show it; services don’t know Flutter exists.</p><p><strong>Business rules inside </strong>build(), <strong>like</strong> if (post.likes &gt; 100).<br><strong>Instead</strong>: decide it in the model, the service or the state. The widget only draws.</p><p><strong>Storing error messages as strings in the state.<br>Instead</strong>: store the failure and translate it in the UI, so messages stay consistent and can be localized.</p><p><strong>One giant </strong>utils/ <strong>folder</strong>.<br><strong>Instead</strong>: keep code in the feature it belongs to. Move it to core/ when a second feature needs it.</p><p><strong>Over-engineering: an interface, a use case and a mapper for every getter.<br>Instead</strong>: add structure when it solves a problem you actually have.</p><h3>Try it yourself</h3><p>Everything in this article comes from the <a href="https://github.com/valentynapolienova/flutter_clean_architecture_template">Flutter Clean Architecture Template on GitHub</a>. It’s free to use.</p><pre>git clone --depth 1 https://github.com/valentynapolienova/flutter_clean_architecture_template.git my_app<br>cd my_app<br>./tool/rename.sh my_app com.example &quot;My App&quot;<br>fvm flutter pub get<br>fvm flutter run -t lib/main_dev.dart --dart-define-from-file=env/dev.json</pre><p>Tap <strong>Use demo account</strong>, scroll the posts, search, open one. Then switch on airplane mode and try again, and watch the error handling do its job.</p><p><strong>A small exercise.</strong> Show a heart icon on posts with more than 100 likes. Before you write any code, decide where each piece goes:</p><ul><li><strong>The rule</strong> “more than 100 likes means popular” is part of what a post is, so it goes in <strong>Domain</strong>: bool get isPopular =&gt; likes &gt; 100; on Post.</li><li><strong>The heart</strong> is drawing, so it goes in Presentation, inside PostTile.</li><li><strong>The data layer doesn’t change at all.</strong> The API already sends the likes.</li></ul><p>If you could answer that in a few seconds, you’ve got it.</p><h3>Cheat sheet</h3><ul><li><strong>“What does the screen show?”</strong> → Presentation: pages and widgets.</li><li><strong>“What state is the screen in?”</strong> → Presentation: Cubit and state.</li><li><strong>“What are the rules?”</strong> → Application: services.</li><li><strong>“Where does the data come from, and what does the JSON look like?”</strong> → Data: repositories and DTOs.</li><li><strong>“What is a Post?”</strong> → Domain: models.</li><li><strong>“What do all features share?” </strong>→ core/.</li><li><strong>“How does the app start and navigate?” </strong>→ app/.</li></ul><p>Clean architecture isn’t about folders or fancy words. <strong>It’s about making the next change cheap.</strong> If you can answer “where does this code go?” in two seconds, you’re doing it right.</p><p>The template: <a href="https://github.com/valentynapolienova/flutter_clean_architecture_template">github.com/valentynapolienova/flutter_clean_architecture_template</a>. Clone it, rename it and start building.</p><p>Further reading: <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">The Clean Architecture</a> by Robert C. Martin, <a href="https://codewithandrea.com/articles/flutter-app-architecture-riverpod-introduction/">Flutter App Architecture with Riverpod</a> by Andrea Bizzotto, and the <a href="https://bloclibrary.dev/">bloc library documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b00aa22ffad3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Step-by-Step Guide to Deep Links in Flutter]]></title>
            <link>https://medium.com/@m1nori/a-step-by-step-guide-to-deep-links-in-flutter-572651fc9397?source=rss-943a64474b36------2</link>
            <guid isPermaLink="false">https://medium.com/p/572651fc9397</guid>
            <category><![CDATA[universal-links]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[deep-linking]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Valentyna Polienova]]></dc:creator>
            <pubDate>Wed, 09 Sep 2026 11:56:12 GMT</pubDate>
            <atom:updated>2026-09-09T11:56:12.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dmrmTfKt4tQLr2ZBbgcYQ.png" /><figcaption>Guide to Deep Links in Flutter</figcaption></figure><p>Add Android App Links and iOS Universal Links to a Flutter app, route users to the correct content, and provide a useful fallback when the app is not installed.</p><p>Imagine that someone finds a useful article in your app and shares it with a friend:</p><pre>I thought you might like this article.<br>https://links.example.com/articles/123</pre><p>The experience should feel effortless:</p><p>• If the app is installed, the link opens article 123 in the app.<br>• If the app is not installed, the link opens a web page with App Store and Google Play options.<br>• If the user needs to sign in, the app remembers the link and opens the article after authentication.</p><p>Android App Links and iOS Universal Links are designed for exactly this purpose. Both use ordinary HTTPS URLs, so links remain useful outside the app and are protected through domain verification.</p><p>In this guide, we will add this flow to a Flutter app using <strong>go_router</strong>.</p><p>Our example link will be:</p><pre>https://links.example.com/articles/:articleId</pre><p>You can replace the domain, path, and content type with your own.</p><h3>How the pieces fit together</h3><p>A working deep link needs three layers to agree:</p><ol><li>Your website hosts verification files identifying the Android and iOS apps allowed to open its links.</li><li>The native applications declare the domains and URL paths they support.</li><li>Flutter routing converts the incoming path into an in-app destination.</li></ol><p>Your website also needs a <strong>fallback page</strong>.</p><p>App Links and Universal Links <strong>do not</strong> automatically send someone to an app store when the app is missing. If the operating system cannot find an installed app for the link, it opens the HTTPS address in a browser.</p><p>Let’s build each layer.</p><h3>Step 1: Decide your link structure</h3><p>Do this before editing either app.</p><p>A stable URL is a small public API. Shared links may remain in messages, emails, and search results for years.</p><p>Decide the following:</p><p>• The domain, such as <strong>links.example.com</strong>.<br>• The path format, such as <strong>/articles/:articleId</strong>.<br>• Whether development, staging, and production use separate domains.<br>• The <strong>Android application ID</strong> and <strong>signing-certificate fingerprint</strong> for each build.<br>• The <strong>Apple Team ID</strong> and <strong>iOS bundle ID</strong> for each build.<br>• The <strong>App Store</strong> and <strong>Google Play addresses</strong> used by the fallback page.</p><p>Choose one canonical spelling and use it everywhere.</p><p>For applications with multiple environments, separate domains are often the clearest option:</p><blockquote>Development: <strong>links.dev.example.com</strong><br>Staging: <strong>links.staging.example.com</strong><br>Production: <strong>links.example.com</strong></blockquote><p>Each domain must serve its own verification files. It should also be publicly reachable because devices and platform verification services need access to it.</p><h3>Step 2: Create the browser fallback</h3><p>Before touching Flutter, make sure your link works in a normal browser:</p><pre>https://links.example.com/articles/123</pre><p>The page can include:</p><p>• A short explanation of the content.<br>• An “Open the app” action.<br>• An App Store button.<br>• A Google Play button.</p><p>You can <strong>redirect</strong> users to the appropriate store <strong>after detecting their platform</strong>. However, visible store buttons provide a safer fallback when platform detection fails or someone opens the link on a desktop.</p><p>If you already have a web version of the content, display it and offer the app as an enhanced experience.</p><p>The important part is that the URL remains useful when no installed app intercepts it.</p><h3>Step 3: Prove the Android association</h3><p>Android verifies your domain using a Digital Asset Links file.</p><p>Create an assetlinks.json file and host it at:</p><pre>https://links.example.com/.well-known/assetlinks.json</pre><p>Its contents should look like this:</p><pre>[<br>  {<br>    &quot;relation&quot;: [&quot;delegate_permission/common.handle_all_urls&quot;],<br>    &quot;target&quot;: {<br>      &quot;namespace&quot;: &quot;android_app&quot;,<br>      &quot;package_name&quot;: &quot;com.example.reader&quot;,<br>      &quot;sha256_cert_fingerprints&quot;: [<br>        &quot;AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99&quot;<br>      ]<br>    }<br>  }<br>]</pre><p>Replace the<strong> package name and fingerprint</strong> with your real values.</p><p>For a locally signed build, you can inspect the keystore with:</p><pre>keytool -list -v -keystore &lt;path-to-keystore&gt;</pre><p><strong>If you use Play App Signing, use the app-signing certificate fingerprint shown in Play Console.</strong></p><p>This is important: the upload certificate on your machine is usually not the certificate attached to the app installed from Google Play.</p><p>The <strong>assetlinks.json</strong> response must be:</p><p>• Available over HTTPS.<br>• Publicly accessible.<br>• Served with the application/json content type.<br>• Returned directly, without a 301 or 302 redirect.</p><p>One file can contain multiple statements if several applications or build variants are authorized for the domain. It can also contain multiple certificate fingerprints for the same application ID.</p><h3>Step 4: Register the link in Android</h3><p>Open:</p><pre>android/app/src/main/AndroidManifest.xml</pre><p>Inside the <strong>MainActivity</strong> declaration, add this intent filter:</p><pre>&lt;intent-filter android:autoVerify=&quot;true&quot;&gt;<br>    &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot; /&gt;</pre><pre>    &lt;data<br>        android:scheme=&quot;https&quot;<br>        android:host=&quot;links.example.com&quot;<br>        android:pathPrefix=&quot;/articles/&quot; /&gt;<br>&lt;/intent-filter&gt;</pre><p>The <strong>android:autoVerify=”true”</strong> value asks Android to fetch <strong>assetlinks.json</strong> and confirm that your website authorizes the app.</p><p>If your project has build <strong>flavors</strong>, replace the literal host with a manifest placeholder:</p><pre>android:host=&quot;${deepLinkHost}&quot;</pre><p>Assign <strong>deepLinkHost</strong> in each flavor’s Gradle configuration.</p><p>This prevents a development build from claiming production links. It also keeps the shared URL generated by Flutter consistent with the native app configuration.</p><p>Flutter’s built-in deep-link handler is enabled by default in Flutter 3.27 and later.</p><p>For earlier versions, add this inside the activity:</p><pre>&lt;meta-data<br>    android:name=&quot;flutter_deeplinking_enabled&quot;<br>    android:value=&quot;true&quot; /&gt;</pre><p>If you use a third-party deep-link plugin, follow its setup instructions and disable Flutter’s built-in handler. You should not have two handlers competing for the same incoming link.</p><h3>Step 5: Prove the iOS association</h3><p>iOS uses an Apple App Site Association file, commonly called the AASA file.</p><p>Host it without a file extension at:</p><pre>https://links.example.com/.well-known/apple-app-site-association</pre><p>For our article route, the file can contain:</p><pre>{<br>  &quot;applinks&quot;: {<br>    &quot;details&quot;: [<br>      {<br>        &quot;appIDs&quot;: [<br>          &quot;ABCDE12345.com.example.reader&quot;<br>        ],<br>        &quot;components&quot;: [<br>          {<br>            &quot;/&quot;: &quot;/articles/*&quot;,<br>            &quot;comment&quot;: &quot;Open articles in the app&quot;<br>          }<br>        ]<br>      }<br>    ]<br>  }<br>}</pre><p>Each app ID has the following format:</p><pre>&lt;Apple Team ID&gt;.&lt;bundle ID&gt;</pre><p>Like <strong>assetlinks.json</strong>, the AASA file must be served over HTTPS without redirects. Serve it as JSON and keep it publicly accessible.</p><p>Apple retrieves associated-domain files through its own content delivery network, so new or updated files can take time to propagate.</p><p>You can list multiple app IDs in one AASA file. This is useful when several build flavors share a domain, although separate domains make it easier to prevent two installed variants from competing for the same URL.</p><h3>Step 6: Enable Associated Domains on iOS</h3><p>Open the following workspace in Xcode:</p><pre>ios/Runner.xcworkspace</pre><p>Select the <strong>Runner</strong> target and open <strong>Signing &amp; Capabilities</strong>.</p><p>Add the <strong>Associated Domains</strong> capability and enter:</p><pre>applinks:links.example.com</pre><p>The resulting <strong>Runner.entitlements</strong> entry should look like this:</p><pre>&lt;key&gt;com.apple.developer.associated-domains&lt;/key&gt;<br>&lt;array&gt;<br>    &lt;string&gt;applinks:links.example.com&lt;/string&gt;<br>&lt;/array&gt;</pre><p>Enable the capability for every App ID and build configuration that should receive links.</p><p>For multiple environments, use the matching domain in each configuration.</p><p>For example:</p><p><strong>Development</strong>:</p><pre>applinks:links.dev.example.com</pre><p><strong>Production</strong>:</p><pre>applinks:links.example.com</pre><p>As on Android, Flutter 3.27 and later enables its built-in deep-link handler by default.</p><p><strong>Older projects</strong> need this value in <strong>Info.plist</strong>:</p><pre>&lt;key&gt;FlutterDeepLinkingEnabled&lt;/key&gt;<br>&lt;true/&gt;</pre><h3>Step 7: Map the URL to a Flutter screen</h3><p>Add go_router if the application does not already use it:</p><pre>flutter pub add go_router</pre><p>Create a route whose path exactly matches the public link structure:</p><pre>final router = GoRouter(<br>  routes: [<br>    GoRoute(<br>      path: &#39;/articles/:articleId&#39;,<br>      builder: (context, state) {<br>        final articleId = int.tryParse(<br>          state.pathParameters[&#39;articleId&#39;] ?? &#39;&#39;,<br>        );</pre><pre>        if (articleId == null) {<br>          return const ErrorPage();<br>        }</pre><pre>        return ArticlePage(articleId: articleId);<br>      },<br>    ),<br>  ],<br>);</pre><p>Pass the router to your application:</p><pre>MaterialApp.router(<br>  routerConfig: router,<br>)</pre><p>When Flutter receives this link:</p><pre>https://links.example.com/articles/123</pre><p><strong>go_router</strong> uses the <strong>/articles/123 path</strong>, extracts 123, and builds the article page.</p><p>If your application uses bottom navigation, place the article route in the branch that owns the article experience.</p><p>A root-level deep link should be able to construct the correct navigation stack even when the application starts from a terminated state.</p><p>You should also handle a valid-looking ID whose content no longer exists. A deleted article should display a clear not-found or error screen instead of a blank page or endless loader.</p><h3>Step 8: Preserve the destination through login</h3><p>Authentication is where otherwise good deep-link implementations often break.</p><p>Redirecting a logged-out user to the login screen is not enough. You must retain the original destination.</p><p>One simple approach is to include it as a query parameter:</p><pre>redirect: (context, state) {<br>  final onLoginPage = state.matchedLocation == &#39;/login&#39;;</pre><pre>  if (!auth.isSignedIn &amp;&amp; !onLoginPage) {<br>    return Uri(<br>      path: &#39;/login&#39;,<br>      queryParameters: {<br>        &#39;redirect&#39;: state.uri.toString(),<br>      },<br>    ).toString();<br>  }</pre><pre>  return null;<br>},</pre><p>After a successful login, navigate to the saved internal location:</p><pre>final redirect = GoRouterState.of(<br>  context,<br>).uri.queryParameters[&#39;redirect&#39;];</pre><pre>context.go(redirect ?? &#39;/&#39;);</pre><p>Connect the router’s refresh mechanism to your authentication state so that redirects are evaluated again when the user’s login status changes.</p><p>Treat the saved destination as an internal application path and validate it before navigation. If you store pending links separately, clear them after they have been used.</p><p>Test this flow from a terminated app as well as while the app is already running. Cold-start timing often exposes problems that normal navigation does not.</p><h3>Step 9: Add the share action</h3><p>Add <strong>share_plus</strong>:</p><pre>flutter pub add share_plus</pre><p>Keep the link’s base URL in your environment configuration. Then build the full URL using Dart’s Uri API:</p><pre>import &#39;package:share_plus/share_plus.dart&#39;;</pre><pre>Future&lt;void&gt; shareArticle({<br>  required int articleId,<br>  required String shareBaseUrl,<br>}) async {<br>  final baseUri = Uri.parse(shareBaseUrl);<br>  final articleUri = baseUri.replace(<br>    pathSegments: [<br>      ...baseUri.pathSegments,<br>      &#39;articles&#39;,<br>      &#39;$articleId&#39;,<br>    ],<br>  );</pre><pre>  await SharePlus.instance.share(<br>    ShareParams(<br>      text:<br>          &#39;I thought you might like this article.\n$articleUri&#39;,<br>      subject: &#39;An article for you&#39;,<br>    ),<br>  );<br>}</pre><p>Using environment configuration instead of a hardcoded production address lets every build flavor generate links for the domain it is registered to open.</p><h3>Step 10: Verify</h3><p>Do not stop after confirming that the correct page opens once.</p><p>Deep linking crosses your server, mobile operating system, application lifecycle, router, authentication flow, and content API. You need to test all of them together.</p><p><strong>Checking the hosted files</strong></p><p>Run:</p><pre>curl -i https://links.example.com/.well-known/assetlinks.json</pre><pre>curl -i <a href="https://links.example.com/.well-known/apple-app-site-association">https://links.example.com/.well-known/apple-app-site-association</a></pre><p>Confirm that each request returns:</p><p>• A successful response.<br>• The expected JSON.<br>• The correct content type.<br>• No redirect.</p><p><strong>Verifying Android App Links</strong></p><p>On Android 12 or later, reset the existing state and request verification:</p><pre>adb shell pm set-app-links --package com.example.reader 0 all</pre><pre>adb shell pm verify-app-links --re-verify com.example.reader</pre><pre>adb shell pm get-app-links com.example.reader</pre><p>Wait for verification to complete and look for verified beside your domain.</p><p>Then launch an unqualified web intent so that Android resolves it normally:</p><pre>adb shell am start \<br>  -a android.intent.action.VIEW \<br>  -c android.intent.category.BROWSABLE \<br>  -d &quot;https://links.example.com/articles/123&quot;</pre><p>Also tap the link from a message, email, or web page.</p><p>A command that explicitly names your application package can prove that the route works, but it may bypass the domain-selection behavior you actually need to test.</p><p><strong>Verifying iOS Universal Links</strong></p><p>For the iOS Simulator, run:</p><pre>xcrun simctl openurl booted \<br>  https://links.example.com/articles/123</pre><p>On a physical device, place the link in Notes or Messages and tap it.</p><p>Do not use typing or pasting the URL directly into Safari’s address bar as your only test. Direct browser navigation does not behave like tapping a Universal Link.</p><p>If a new AASA file looks correct but the link still opens in the browser, allow time for Apple’s CDN to retrieve it. Reinstall the app after the association becomes available.</p><h4>The complete test checklist</h4><p>• App installed and user signed in: the correct content opens.<br>• App installed and user signed out: login opens first, followed by the original content.<br>• App terminated: the app launches at the correct destination.<br>• App in the background: the existing app navigates to the destination.<br>• App not installed: the fallback web page opens.<br>• Invalid or missing ID: the app displays a useful error state.<br>• Development, staging, and production: each build opens only its own domain.<br>• Android and iOS: both platforms are tested on real devices.</p><h3>Common mistakes to avoid</h3><p>• Using different paths in the router, native configuration, and AASA file.<br>• Publishing verification files behind a redirect or authentication wall.<br>• Using the Android upload-key fingerprint instead of the Play App Signing fingerprint.<br>• Forgetting to configure every build flavor.<br>• Hardcoding the production share domain in all builds.<br>• Losing the incoming destination during login.<br>• Testing only while the app is already running.<br>• Assuming an absent app automatically sends the user to an app store.<br>• Expecting a new iOS association to propagate immediately.</p><h3>The result</h3><p>You now have one durable HTTPS URL that works everywhere.</p><p>Installed users move directly into the correct screen. Signed-out users return there after authentication. Everyone else gets a useful web fallback.</p><p>The code is the short part.</p><p>The real key is agreement: one canonical URL shared by your website, Android configuration, iOS configuration, Flutter router, authentication flow, and environment settings.</p><p>Get that contract right, and deep links stop feeling mysterious.</p><p>Further reading: <a href="https://docs.flutter.dev/ui/navigation/deep-linking">Flutter deep linking</a>, <a href="https://developer.android.com/training/app-links/configure-assetlinks">Android App Links</a>, and <a href="https://developer.apple.com/documentation/xcode/supporting-associated-domains">Apple Associated Domains</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=572651fc9397" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Hide a Bottom Navigation Bar on Scroll in Flutter]]></title>
            <link>https://medium.com/@m1nori/how-to-hide-a-bottom-navigation-bar-on-scroll-in-flutter-234d47a7553e?source=rss-943a64474b36------2</link>
            <guid isPermaLink="false">https://medium.com/p/234d47a7553e</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[bottomnavigationbar]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Valentyna Polienova]]></dc:creator>
            <pubDate>Tue, 24 Mar 2026 13:19:04 GMT</pubDate>
            <atom:updated>2026-04-20T08:12:01.642Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometimes a bottom navigation bar takes up too much space, especially on content-heavy screens like search, lists, or article pages. A small interaction like hiding it while the user scrolls down and bringing it back when they scroll up can make the UI feel much cleaner and more natural.</p><p>In this example, I made a simple reusable Flutter widget that listens to scroll direction and controls the visibility of the bottom navigation bar through a <strong>ValueNotifier</strong>.</p><p>I also added a couple of practical details, like <strong>resetting the state on route changes</strong> and <strong>restoring visibility when the content is no longer scrollable</strong>.</p><p>Even though I’m using it here for a bottom navigation bar, the same approach can be reused for many other UI elements like floating buttons, action panels, or toolbars, and it becomes even nicer when paired with a small animation.</p><pre>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:flutter/rendering.dart&#39;;<br>import &#39;package:flutter/widgets.dart&#39;;<br><br>/// Shared controller for the visibility state of a bottom overlay element.<br>final ValueNotifier&lt;bool&gt; bottomOverlayVisibility = ValueNotifier&lt;bool&gt;(true);<br><br>/// Wrap a scrollable widget with this to toggle bottom overlay visibility<br>/// based on scroll direction.<br>class ScrollVisibilityListener extends StatefulWidget {<br>  const ScrollVisibilityListener({<br>    required this.child,<br>    this.enabled = true,<br>    super.key,<br>  });<br><br>  /// Whether the hide/show behavior is active.<br>  final bool enabled;<br><br>  /// The scrollable content to observe.<br>  final Widget child;<br><br>  @override<br>  State&lt;ScrollVisibilityListener&gt; createState() =&gt;<br>      _ScrollVisibilityListenerState();<br>}<br><br>class _ScrollVisibilityListenerState extends State&lt;ScrollVisibilityListener&gt; {<br>  ScrollDirection _lastDirection = ScrollDirection.idle;<br><br>  @override<br>  void didUpdateWidget(covariant ScrollVisibilityListener oldWidget) {<br>    super.didUpdateWidget(oldWidget);<br><br>    if (oldWidget.enabled != widget.enabled &amp;&amp; !widget.enabled) {<br>      _resetVisibility();<br>    }<br>  }<br><br>  @override<br>  void dispose() {<br>    _resetVisibility();<br>    super.dispose();<br>  }<br><br>  void _resetVisibility() {<br>    bottomOverlayVisibility.value = true;<br>    _lastDirection = ScrollDirection.idle;<br>  }<br><br>  bool _handleNotification(Notification notification) {<br>    if (!widget.enabled) return false;<br><br>    if (notification is ScrollMetricsNotification) {<br>      final isScrollable = notification.metrics.maxScrollExtent &gt; 0;<br><br>      if (!isScrollable &amp;&amp; !bottomOverlayVisibility.value) {<br>        _resetVisibility();<br>      }<br><br>      return false;<br>    }<br><br>    if (notification is UserScrollNotification) {<br>      final direction = notification.direction;<br><br>      if (direction == ScrollDirection.idle ||<br>          direction == _lastDirection) {<br>        return false;<br>      }<br><br>      _lastDirection = direction;<br>      bottomOverlayVisibility.value =<br>          direction == ScrollDirection.forward;<br>    }<br><br>    return false;<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return NotificationListener&lt;Notification&gt;(<br>      onNotification: _handleNotification,<br>      child: widget.child,<br>    );<br>  }<br>}</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*u8fnJyp1LsEpB_N7ERRi2Q.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=234d47a7553e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prevent Screenshots and Screen Recordings in Flutter]]></title>
            <link>https://medium.com/@m1nori/prevent-screenshots-and-screen-recordings-in-flutter-ea7b911c9220?source=rss-943a64474b36------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea7b911c9220</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Valentyna Polienova]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 17:45:21 GMT</pubDate>
            <atom:updated>2026-03-19T17:45:21.347Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone! Let’s take a quick look at the native options for preventing screenshots and screen recordings on iOS and Android.</p><h3>Bottom line</h3><ul><li><strong>Android:</strong> we can block screenshots on sensitive screens and also detect when a screenshot is taken, so the app can react if needed. Docs:<br><a href="https://developer.android.com/about/versions/14/features/screenshot-detection?utm_source=chatgpt.com">Detect when users take device screenshots | Android Developers</a> <br><a href="https://developer.android.com/security/fraud-prevention/activities?utm_source=chatgpt.com">Secure sensitive activities | Fraud prevention | Android Developers</a></li><li><strong>iOS:</strong> we can detect that a screenshot was taken, but there is no supported public API to fully prevent screenshots in the general case. Apple provides a screenshot notification, not a screenshot-blocking API.<br>As a workaround, some apps use <strong>isSecureTextEntry</strong> — originally intended for protecting sensitive text input — to render content in a “secure” context that is excluded from system capture. Docs:<br><a href="https://developer.apple.com/documentation/uikit/uiapplication/userdidtakescreenshotnotification?utm_source=chatgpt.com">userDidTakeScreenshotNotification | Apple Developer Documentation</a><br><a href="https://developer.apple.com/documentation/uikit/uiscreen/captureddidchangenotification?utm_source=chatgpt.com">capturedDidChangeNotification | Apple Developer Documentation</a> <br><a href="https://developer.apple.com/documentation/uikit/uitraitcollection/scenecapturestate">sceneCaptureState | Apple Developer Documentation</a> <br><a href="https://developer.apple.com/documentation/uikit/uitextinputtraits/issecuretextentry">isSecureTextEntry | Apple Developer Documentation</a></li></ul><h3>Implementation</h3><ol><li><strong>iOS</strong></li></ol><p>Modify your ios/Runner/<strong>AppDelegate.swift</strong></p><pre>import UIKit<br>import Flutter<br><br>@main<br>@objc class AppDelegate: FlutterAppDelegate {<br><br>    private var secureField: UITextField?<br>    private var windowSuperlayer: CALayer?<br><br>    override func application(<br>        _ application: UIApplication,<br>        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?<br>    ) -&gt; Bool {<br>        GeneratedPluginRegistrant.register(with: self)<br><br>        guard let controller = window?.rootViewController as? FlutterViewController else {<br>            return super.application(application, didFinishLaunchingWithOptions: launchOptions)<br>        }<br><br>        FlutterMethodChannel(name: &quot;screenProtectorChannel&quot;, binaryMessenger: controller.binaryMessenger)<br>            .setMethodCallHandler { [weak self] call, result in<br>                switch call.method {<br>                case &quot;enableScreenProtector&quot;:<br>                    self?.enableScreenProtector()<br>                    result(&quot;Screen protector enabled&quot;)<br>                case &quot;disableScreenProtector&quot;:<br>                    self?.disableScreenProtector()<br>                    result(&quot;Screen protector disabled&quot;)<br>                default:<br>                    result(FlutterMethodNotImplemented)<br>                }<br>            }<br><br>        return super.application(application, didFinishLaunchingWithOptions: launchOptions)<br>    }<br><br>    private func enableScreenProtector() {<br>        guard secureField == nil, let window = self.window else { return }<br><br>        let field = UITextField()<br>        field.isSecureTextEntry = true<br><br>        windowSuperlayer = window.layer.superlayer<br>        window.layer.superlayer?.addSublayer(field.layer)<br>        field.layer.sublayers?.last?.addSublayer(window.layer)<br><br>        secureField = field<br>    }<br><br>    private func disableScreenProtector() {<br>        guard let field = secureField, let window = self.window else { return }<br><br>        // Restore window.layer to its original position BEFORE removing the field layer,<br>        // otherwise window.layer gets removed along with the field and causes a black screen.<br>        windowSuperlayer?.addSublayer(window.layer)<br>        field.layer.removeFromSuperlayer()<br><br>        secureField = nil<br>        windowSuperlayer = nil<br>    }<br>}</pre><p>2. <strong>Android</strong></p><p>Modify your android/app/src/main/kotlin/<strong>MainActivity.kt</strong></p><pre>package com.example.screenshot_test<br><br>import android.view.WindowManager<br>import io.flutter.embedding.android.FlutterActivity<br>import io.flutter.embedding.engine.FlutterEngine<br>import io.flutter.plugin.common.MethodChannel<br><br>class MainActivity : FlutterActivity() {<br>    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {<br>        super.configureFlutterEngine(flutterEngine)<br><br>        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, &quot;screenProtectorChannel&quot;)<br>            .setMethodCallHandler { call, result -&gt;<br>                when (call.method) {<br>                    &quot;enableScreenProtector&quot; -&gt; {<br>                        window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)<br>                        result.success(&quot;Screen protector enabled&quot;)<br>                    }<br>                    &quot;disableScreenProtector&quot; -&gt; {<br>                        window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)<br>                        result.success(&quot;Screen protector disabled&quot;)<br>                    }<br>                    else -&gt; result.notImplemented()<br>                }<br>            }<br>    }<br>}</pre><p>3. Add protection to your page. Here is a simple usage example:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br><br>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br><br>  await ScreenProtector.enable();<br><br>  runApp(const MyApp());<br>}<br><br>class ScreenProtector {<br>  static const MethodChannel _channel = MethodChannel(&#39;screenProtectorChannel&#39;);<br><br>  static Future&lt;void&gt; enable() async {<br>    try {<br>      await _channel.invokeMethod(&#39;enableScreenProtector&#39;);<br>    } on PlatformException catch (e) {<br>      debugPrint(&#39;Failed to enable screen protector: ${e.message}&#39;);<br>    }<br>  }<br><br>  static Future&lt;void&gt; disable() async {<br>    try {<br>      await _channel.invokeMethod(&#39;disableScreenProtector&#39;);<br>    } on PlatformException catch (e) {<br>      debugPrint(&#39;Failed to disable screen protector: ${e.message}&#39;);<br>    }<br>  }<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Screen Protector Demo&#39;,<br>      debugShowCheckedModeBanner: false,<br>      home: const HomePage(),<br>    );<br>  }<br>}<br><br>class HomePage extends StatefulWidget {<br>  const HomePage({super.key});<br><br>  @override<br>  State&lt;HomePage&gt; createState() =&gt; _HomePageState();<br>}<br><br>class _HomePageState extends State&lt;HomePage&gt; {<br>  bool _enabled = true;<br><br>  Future&lt;void&gt; _toggleGuard() async {<br>    if (_enabled) {<br>      await ScreenProtector.disable();<br>    } else {<br>      await ScreenProtector.enable();<br>    }<br><br>    setState(() {<br>      _enabled = !_enabled;<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&#39;Screen Protector Demo&#39;)),<br>      body: Center(<br>        child: Column(<br>          mainAxisSize: MainAxisSize.min,<br>          children: [<br>            Text(<br>              _enabled ? &#39;Protection enabled&#39; : &#39;Protection disabled&#39;,<br>              style: const TextStyle(fontSize: 18),<br>            ),<br>            const SizedBox(height: 16),<br>            ElevatedButton(<br>              onPressed: _toggleGuard,<br>              child: Text(_enabled ? &#39;Disable protector&#39; : &#39;Enable protector&#39;),<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*8AJUJFeixQubliuyTw6YaQ.gif" /></figure><p>That’s it — you now have a simple cross-platform screen protection setup for Flutter.</p><p>Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea7b911c9220" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Pagination On Scroll without any packages v2]]></title>
            <link>https://medium.com/@m1nori/flutter-pagination-on-scroll-without-any-packages-v2-906424745bb6?source=rss-943a64474b36------2</link>
            <guid isPermaLink="false">https://medium.com/p/906424745bb6</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[infinite-scroll]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[pagination]]></category>
            <dc:creator><![CDATA[Valentyna Polienova]]></dc:creator>
            <pubDate>Thu, 13 Nov 2025 11:39:39 GMT</pubDate>
            <atom:updated>2026-09-09T12:54:21.597Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey guys! Over the last few years I’ve been refining my approach to pagination in Flutter. After a lot of trial, error, and patterns that didn’t scale well, I ended up with a clean, reusable solution that I now drop into every project.</p><p>So, to continue the topic from my <a href="https://medium.com/@m1nori/flutter-pagination-without-any-packages-8c24095555b3">previous article</a>, I want to share the final version of this helper.</p><p>Let’s jump in!</p><h3><strong>1. Add the infinite-scroll listener</strong></h3><pre>import &#39;dart:async&#39;;<br><br>import &#39;package:flutter/material.dart&#39;;<br><br>class InfiniteScrollController extends ChangeNotifier {<br>  void reset() =&gt; notifyListeners();<br>}<br><br>class InfiniteScrollListener extends StatefulWidget {<br>  const InfiniteScrollListener({<br>    required this.scrollController,<br>    required this.onLoadMore,<br>    required this.child,<br>    this.isFinished = false,<br>    this.triggerOffset = 100,<br>    this.controller,<br>    super.key,<br>  }) : assert(triggerOffset &gt;= 0);<br><br>  final ScrollController scrollController;<br>  final Future&lt;bool&gt; Function() onLoadMore;<br>  final Widget child;<br>  final bool isFinished;<br>  final double triggerOffset;<br>  final InfiniteScrollController? controller;<br><br>  @override<br>  State&lt;InfiniteScrollListener&gt; createState() =&gt;<br>      _InfiniteScrollListenerState();<br>}<br><br>class _InfiniteScrollListenerState extends State&lt;InfiniteScrollListener&gt; {<br>  bool _isFetching = false;<br>  bool _isArmed = true;<br>  bool _checkScheduled = false;<br>  bool _resetPending = false;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    widget.scrollController.addListener(_handleScroll);<br>    widget.controller?.addListener(_reset);<br>    _scheduleCheck();<br>  }<br><br>  @override<br>  void didUpdateWidget(covariant InfiniteScrollListener oldWidget) {<br>    super.didUpdateWidget(oldWidget);<br><br>    if (oldWidget.scrollController != widget.scrollController) {<br>      oldWidget.scrollController.removeListener(_handleScroll);<br>      widget.scrollController.addListener(_handleScroll);<br>      _isArmed = true;<br>    }<br><br>    if (oldWidget.controller != widget.controller) {<br>      oldWidget.controller?.removeListener(_reset);<br>      widget.controller?.addListener(_reset);<br>    }<br><br>    if (oldWidget.isFinished &amp;&amp; !widget.isFinished) {<br>      _isArmed = true;<br>    }<br><br>    _scheduleCheck();<br>  }<br><br>  void _handleScroll() {<br>    final controller = widget.scrollController;<br>    if (!controller.hasClients || controller.positions.length != 1) {<br>      return;<br>    }<br><br>    final position = controller.position;<br>    if (!position.hasContentDimensions) {<br>      return;<br>    }<br><br>    if (position.extentAfter &gt; widget.triggerOffset) {<br>      if (!_isFetching) {<br>        _isArmed = true;<br>      }<br>      return;<br>    }<br><br>    if (widget.isFinished || _isFetching || !_isArmed) {<br>      return;<br>    }<br><br>    _isArmed = false;<br>    _isFetching = true;<br>    unawaited(_loadMore());<br>  }<br><br>  Future&lt;void&gt; _loadMore() async {<br>    var shouldCheckAgain = false;<br><br>    try {<br>      shouldCheckAgain = await widget.onLoadMore();<br>    } catch (error, stackTrace) {<br>      FlutterError.reportError(<br>        FlutterErrorDetails(<br>          exception: error,<br>          stack: stackTrace,<br>          library: &#39;infinite scroll listener&#39;,<br>        ),<br>      );<br>    } finally {<br>      if (!mounted) {<br>        return;<br>      }<br><br>      _isFetching = false;<br><br>      if (shouldCheckAgain || _resetPending) {<br>        _isArmed = true;<br>        _resetPending = false;<br>        _scheduleCheck();<br>      }<br>    }<br>  }<br><br>  void _reset() {<br>    if (_isFetching) {<br>      _resetPending = true;<br>      return;<br>    }<br><br>    _isArmed = true;<br>    _scheduleCheck();<br>  }<br><br>  void _scheduleCheck() {<br>    if (_checkScheduled) {<br>      return;<br>    }<br><br>    _checkScheduled = true;<br>    WidgetsBinding.instance.addPostFrameCallback((_) {<br>      _checkScheduled = false;<br>      if (mounted) {<br>        _handleScroll();<br>      }<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) =&gt; widget.child;<br><br>  @override<br>  void dispose() {<br>    widget.scrollController.removeListener(_handleScroll);<br>    widget.controller?.removeListener(_reset);<br>    super.dispose();<br>  }<br>}</pre><p>onLoadMore returns true after a page was fetched successfully. That tells the listener to check the layout again. If the list is still close to the bottom, it requests another page.</p><p>This is important on tablets, landscape layouts, and empty screens where one page may not fill the viewport.</p><p>Return false when the request fails or is skipped. The listener will not immediately retry a failed request. It becomes eligible again after the user scrolls away from the threshold and returns, or after controller.reset() is called.</p><p>A ScrollController should be attached to exactly one scrollable while it is used by this widget.</p><h3>2. Keep page state outside the widget</h3><p>The paginator does not need a type parameter because it does not store items. It only tracks the next page and whether the end has been reached.</p><pre>class PagePaginator {<br>  PagePaginator({this.pageSize = 50, this.firstPage = 0})<br>    : assert(pageSize &gt; 0),<br>      _nextPage = firstPage;<br><br>  final int pageSize;<br>  final int firstPage;<br><br>  int _nextPage;<br>  bool _hasReachedEnd = false;<br><br>  int get nextPage =&gt; _nextPage;<br>  bool get hasReachedEnd =&gt; _hasReachedEnd;<br><br>  void acceptPage({required int itemCount}) {<br>    assert(itemCount &gt;= 0);<br>    _nextPage++;<br><br>    if (itemCount &lt; pageSize) {<br>      _hasReachedEnd = true;<br>    }<br>  }<br><br>  void reset() {<br>    _nextPage = firstPage;<br>    _hasReachedEnd = false;<br>  }<br>}</pre><p>This example assumes a zero-based API. Pass firstPage: 1 for a one-based API.</p><p>For cursor pagination, store the next cursor returned by the server instead of incrementing an integer.</p><p>The itemCount &lt; pageSize rule is valid only when the API guarantees full pages until the end. Prefer the server’s hasMore, nextPage, or nextCursor field when one is available.</p><h3>3. Load pages in the Cubit</h3><p>The Cubit needs its own in-flight flag. The widget prevents duplicate calls from scrolling, while the Cubit protects the data source from calls made by other UI actions.</p><pre>final PagePaginator _paginator = PagePaginator(pageSize: 7);<br><br>List&lt;WeatherDay&gt; _days = [];<br>bool _isFetching = false;<br><br>Future&lt;bool&gt; loadNextWeatherPage() =&gt;<br>    _fetchWeatherPage(replace: false);<br><br>Future&lt;bool&gt; refreshWeather() =&gt;<br>    _fetchWeatherPage(replace: true);<br><br>Future&lt;bool&gt; _fetchWeatherPage({<br>  required bool replace,<br>}) async {<br>  if (_isFetching || (!replace &amp;&amp; _paginator.hasReachedEnd)) {<br>    return false;<br>  }<br><br>  _isFetching = true;<br>  emit(<br>    WeatherLoading(<br>      days: _days,<br>      hasReachedEnd: _paginator.hasReachedEnd,<br>    ),<br>  );<br><br>  try {<br>    final result = await _service.getWeatherPage(<br>      page: replace<br>          ? _paginator.firstPage<br>          : _paginator.nextPage,<br>      pageSize: _paginator.pageSize,<br>    );<br><br>    return result.fold(<br>      (failure) {<br>        emit(<br>          WeatherError(<br>            message: failure.message,<br>            days: _days,<br>            hasReachedEnd: _paginator.hasReachedEnd,<br>          ),<br>        );<br>        return false;<br>      },<br>      (newDays) {<br>        if (replace) {<br>          _paginator.reset();<br>        }<br><br>        _paginator.acceptPage(<br>          itemCount: newDays.length,<br>        );<br><br>        _days = replace<br>            ? [...newDays]<br>            : [..._days, ...newDays];<br><br>        emit(<br>          WeatherLoaded(<br>            days: _days,<br>            hasReachedEnd: _paginator.hasReachedEnd,<br>          ),<br>        );<br><br>        return true;<br>      },<br>    );<br>  } finally {<br>    _isFetching = false;<br>  }<br>}</pre><p>Every weather state in this example exposes days and hasReachedEnd.</p><p>The important details are:</p><ul><li>_days is actually updated.</li><li>The page advances only after a successful response.</li><li>Failures return false, preventing automatic retry loops.</li><li>Refresh resets the paginator only after the first-page request succeeds.</li></ul><p>That last point ensures a failed refresh does not corrupt the existing list’s page position.</p><p>If the API can return the same item on adjacent pages, deduplicate by a stable ID before assigning _days. Do not convert the list to a Set unless the model’s equality semantics and insertion-order behavior are exactly what the screen needs.</p><h3>4. Use it on the page</h3><pre>class RefreshablePage extends StatefulWidget {<br>  const RefreshablePage({super.key});<br><br>  @override<br>  State&lt;RefreshablePage&gt; createState() =&gt;<br>      _RefreshablePageState();<br>}<br><br>class _RefreshablePageState<br>    extends State&lt;RefreshablePage&gt; {<br>  final _scrollController = ScrollController();<br>  final _infiniteController =<br>      InfiniteScrollController();<br><br>  Future&lt;void&gt; _refresh() async {<br>    final succeeded = await context<br>        .read&lt;WeatherCubit&gt;()<br>        .refreshWeather();<br><br>    if (succeeded) {<br>      _infiniteController.reset();<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocBuilder&lt;WeatherCubit, WeatherState&gt;(<br>      builder: (context, state) {<br>        return RefreshIndicator(<br>          onRefresh: _refresh,<br>          child: InfiniteScrollListener(<br>            scrollController: _scrollController,<br>            controller: _infiniteController,<br>            isFinished: state.hasReachedEnd,<br>            onLoadMore: context<br>                .read&lt;WeatherCubit&gt;()<br>                .loadNextWeatherPage,<br>            child: ListView.builder(<br>              controller: _scrollController,<br>              physics:<br>                  const AlwaysScrollableScrollPhysics(),<br>              itemCount: state.days.length,<br>              itemBuilder: (context, index) {<br>                final day = state.days[index];<br><br>                return ListTile(<br>                  title: Text(day.toString()),<br>                );<br>              },<br>            ),<br>          ),<br>        );<br>      },<br>    );<br>  }<br><br>  @override<br>  void dispose() {<br>    _infiniteController.dispose();<br>    _scrollController.dispose();<br>    super.dispose();<br>  }<br>}</pre><p>The initial post-frame check means an empty list can load its first page without requiring a fake scroll event.</p><p>After a successful refresh, reset() re-arms pagination for the new data set.</p><p>That is the whole flow: the widget observes scrolling, the paginator tracks page metadata, and the Cubit owns requests and data.</p><p>Keeping those concerns separate makes the behavior easier to test and avoids timers, throttling, and pagination state inside the UI.</p><p>Check out the result!</p><figure><img alt="Pagination example" src="https://cdn-images-1.medium.com/max/524/1*b1Nj4ANOF2sMZAnkIdb_Jg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=906424745bb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Golden Tests Fail in GitHub Actions (Why and How to Fix)]]></title>
            <link>https://medium.com/@m1nori/flutter-golden-tests-fail-in-github-actions-why-and-how-to-fix-65e3b69ee86e?source=rss-943a64474b36------2</link>
            <guid isPermaLink="false">https://medium.com/p/65e3b69ee86e</guid>
            <category><![CDATA[flutter-testing]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[golden-tests]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Valentyna Polienova]]></dc:creator>
            <pubDate>Thu, 01 May 2025 13:18:47 GMT</pubDate>
            <atom:updated>2025-05-01T13:18:47.910Z</atom:updated>
            <content:encoded><![CDATA[<p>Flutter golden tests are a powerful way to ensure your UI doesn’t accidentally break. But if you’re running them in CI (like GitHub Actions) and suddenly get failures, you’re not alone — and it’s often <strong>not your fault</strong>.</p><h3>❌ The Problem</h3><p>Golden tests work by comparing widget screenshots to baseline images. But these screenshots can vary between <strong>platforms</strong>:</p><ul><li>Text rendering is different on <strong>macOS vs Linux</strong></li><li>Anti-aliasing or font hinting may produce <strong>pixel-level noise</strong></li><li>Even invisible differences can lead to test failures like:</li></ul><pre>Golden &quot;goldens/my_widget.png&quot;: Pixel test failed, 1.4% diff detected.</pre><p>If you’re running tests on ubuntu-latest, and you develop on macOS, this mismatch can cause false negatives in CI.</p><h3>✅ The Solution: Run Golden Tests on macOS in CI</h3><p>To solve this, we split our GitHub Actions CI setup:</p><ul><li>Logic/unit tests stay on fast, cheap ubuntu-latest</li><li>Golden tests run separately on macos-latest</li></ul><p>This ensures golden tests run in the <strong>same environment as your dev machine</strong>.</p><h3>🔧 Step-by-Step: How to Set This Up</h3><ol><li><strong>Tag your golden test files</strong></li></ol><p>At the top of any golden test file, add:</p><pre>@Tags([&#39;golden&#39;])<br>library;</pre><p>This allows the CI to filter only golden tests using the — tags=golden flag.</p><p><strong>2. Update your GitHub Actions workflow</strong></p><p>Here’s a minimal golden_tests job for macOS:</p><pre>golden_tests:<br>  name: 🖼️ Golden Tests (macOS)<br>  runs-on: macos-latest<br>  steps:<br>    - uses: actions/checkout@v4<br><br>    - uses: subosito/flutter-action@v2<br>      with:<br>        flutter-version: &#39;3.19.0&#39; # use your version<br>        channel: stable<br><br>    - run: flutter pub get<br><br>    - name: Run golden tests<br>      run: flutter test --tags=golden</pre><p>Add this to your existing workflow.</p><h3>💡 Summary</h3><p>If your golden tests are failing in CI:</p><ul><li><strong>Don’t raise the threshold blindly</strong></li><li>Run golden tests on <strong>macOS</strong></li><li>Use @Tags([‘golden’]) and isolate golden test jobs</li><li>Commit updated images only when changes are visually correct</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65e3b69ee86e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Search Debouncer]]></title>
            <link>https://medium.com/@m1nori/flutter-search-debouncer-bde1dab0ce96?source=rss-943a64474b36------2</link>
            <guid isPermaLink="false">https://medium.com/p/bde1dab0ce96</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[debounce]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mixin]]></category>
            <category><![CDATA[search]]></category>
            <dc:creator><![CDATA[Valentyna Polienova]]></dc:creator>
            <pubDate>Wed, 20 Nov 2024 13:25:08 GMT</pubDate>
            <atom:updated>2024-11-20T13:26:42.348Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MPMtHyITUpDYOT1K.jpg" /></figure><p><strong>Recommended time</strong>: 500ms</p><ol><li>Create a <strong>Debouncer Mixin</strong>:</li></ol><pre>import &#39;dart:async&#39;;<br>import &#39;dart:ui&#39;;<br><br>mixin DebouncerMixin {<br>  Timer? _debounceTimer;<br><br>  void runDebounce(VoidCallback action, {required int milliseconds}) {<br>    _debounceTimer?.cancel();<br>    _debounceTimer = Timer(Duration(milliseconds: milliseconds), action);<br>  }<br><br>  void disposeDebouncer() {<br>    _debounceTimer?.cancel();<br>  }<br>}</pre><p>2. Use it in Search Text Field:</p><pre>class SearchTextField extends StatefulWidget {<br>  const SearchTextField({super.key, required this.onChanged});<br><br>  final Function(String) onChanged;<br><br>  @override<br>  State&lt;SearchTextField&gt; createState() =&gt; _SearchTextFieldState();<br>}<br><br>class _SearchTextFieldState extends State&lt;SearchTextField&gt; with DebouncerMixin {<br>  @override<br>  void dispose() {<br>    disposeDebouncer();<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return TextField(<br>              onChanged: (s) {<br>                runDebounce(() {<br>                  widget.onChanged(s);<br>                }, milliseconds: 500);<br>              },<br>            );<br>  }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bde1dab0ce96" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>