<?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 Dimash Yerimbetov on Medium]]></title>
        <description><![CDATA[Stories by Dimash Yerimbetov on Medium]]></description>
        <link>https://medium.com/@dinmukhammed.yerimbetov?source=rss-1a6d95302e36------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*msRLsS-u5sfCUWH5LFpnrw.jpeg</url>
            <title>Stories by Dimash Yerimbetov on Medium</title>
            <link>https://medium.com/@dinmukhammed.yerimbetov?source=rss-1a6d95302e36------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 13:08:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dinmukhammed.yerimbetov/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[Складной iPhone и Flutter]]></title>
            <link>https://medium.com/@dinmukhammed.yerimbetov/%D1%81%D0%BA%D0%BB%D0%B0%D0%B4%D0%BD%D0%BE%D0%B9-iphone-%D0%B8-flutter-122b80adf928?source=rss-1a6d95302e36------2</link>
            <guid isPermaLink="false">https://medium.com/p/122b80adf928</guid>
            <dc:creator><![CDATA[Dimash Yerimbetov]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 13:47:58 GMT</pubDate>
            <atom:updated>2026-09-14T13:47:58.358Z</atom:updated>
            <content:encoded><![CDATA[<p>Почитал гайдлайны Apple по iPhone Duo и поймал знакомое ощущение. В документации всё звучит спокойно и разумно: берите системную навигацию, дайте приложению нормально менять размер — и большая часть работы сделается сама.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EJqTVuDsswIZIhmx.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RsjWsofrj0Xd9Xbj.png" /></figure><p>А потом вспоминаешь, что пишешь на Flutter.</p><p>Для iOS наше приложение — это один большой UIView, внутри которого мы всё рисуем сами. Поэтому системная магия проходит мимо. NavigationSplitView, который сам схлопывается в одну колонку и знает, где проходит сгиб? Не про нас. Системное окно, которое само отодвигается от складки? Наш диалог встанет ровно по центру, прямо на сгибе, и будет там жить. Тулбар, который на внешнем экране уезжает на боковую грань? Наш AppBar как был сверху, так и останется.</p><p>Ничего не делать, кстати, можно: приложение не сломается. Просто на широком и низком внешнем экране нижняя панель вкладок отъест треть высоты, а кнопка «Отправить» окажется на сгибе.</p><p>Первой посыпется ориентация. На внутреннем экране iOS больше не смотрит, какие ориентации объявило приложение. А значит, привычная проверка orientation == Orientation.landscape перестаёт хоть что-то гарантировать. Вёрстку теперь выбираем по реальной ширине окна: LayoutBuilder и брейкпоинты.</p><p>Хорошая новость: это та же самая работа, что и нормальная поддержка iPad. Если вы её уже проделали, половина пути пройдена.</p><p>Дальше — reserved regions, зарезервированные зоны. Так Apple называет места, поверх которых нельзя рисовать контент, и добавляются они к привычной Safe Area: две фронтальные камеры и полоса сгиба посередине. Разница между ними важная: сгиб режет экран на две части, а камера просто перекрывает кусок.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8YPIX6evLKe3-2JJy4Id8w.png" /><figcaption><em>Панели остаются те же, меняется только то, сколько места занимает каждая. Заштрихованная полоса — зона, куда ничего нажимаемого попадать не должно.</em></figcaption></figure><p>Кое-что у Flutter для этого уже есть. В MediaQuery давно лежит displayFeatures, где у каждой зоны свой тип: fold для сгиба и cutout для выреза под камеру. А DisplayFeatureSubScreen умеет отодвигать диалоги от шарнира. Правда, делалось всё это под андроидные раскладушки. Подхватит ли Flutter новое iOS-API — пока непонятно. А пока не подхватил, путь один: писать плагин и ходить за этими данными в нативный код.</p><p>Самое трудоёмкое — боковые контролы. Apple переносит навигацию и тулбар на грань экрана, и это совсем не «поверните AppBar на 90 градусов». Сверху Back и Close, ниже главное действие, дальше всё остальное. Что не влезло — уезжает в меню «…», причём выдавливает элементы снизу вверх. Ближайший аналог у нас — NavigationRail, но порядок и приоритеты придётся расписывать руками.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70jeZFTzCQdb2F6yNNAiow.png" /><figcaption><em>Слева — то, что Flutter-приложение рисует сегодня. Справа — то, чего ждут гайдлайны.</em></figcaption></figure><p>Дальше пара вещей с оригинальной страницы Apple, которые в пересказах обычно теряются.</p><p>Портретная ориентация на внутреннем экране — исключение. Высоты там хватает, поэтому панели остаются горизонтальными, ровно там, где мы привыкли их видеть. Получается, за одну сессию раскладка управления может смениться трижды, и по задумке человек не должен этого заметить.</p><p>Когда на внутреннем экране открыты два приложения, каждое держит свои кнопки у внешней грани: левое — слева, правое — справа. Привязка идёт к железу, а не к языку, так что даже в иврите и арабском сторона остаётся прежней.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTFJiG9SIXhAiySnC5E3vw.png" /><figcaption><em>Половинки не зеркальные: камера только справа.</em></figcaption></figure><p>Самое полезное на странице — примеры, которые Apple разобрала на своих приложениях. Notes ничего не перестраивает: те же две колонки, просто их ширина подстраивается, чтобы обе оставались читаемыми, пока телефон складывают. Calculator обходится вообще без панелей и занимает всю ширину — для экрана, который не скроллится, это нормально, главное не залезть под Dynamic Island. Mail в закрытом виде показывает либо список писем, либо само письмо, а в раскрытом — и то и другое сразу. И кнопки, которые относятся к списку, остаются над списком, а не уезжают на общую боковую панель.</p><p>Есть и вполне практичное правило на случай, когда тулбар и панель вкладок вместе не помещаются. Если экран про навигацию, оставляем вкладки, а действия прячем в меню «…» — так система поступает по умолчанию. Если экран про конкретную задачу, наоборот: вкладки сворачиваем в одну кнопку, действия оставляем. И раз в меню элементы уходят снизу вверх, всему важному нужно явно проставить приоритет: «Написать» в Mail, «Новая заметка» в Notes, любые иконки со счётчиками.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8UxHZ9uRoS6gO7AOjKl1pg.png" /><figcaption><em>Слева — навигационный экран, справа — экран под задачу.</em></figcaption></figure><p>Arrangement view — новый контейнер для двух блоков, и бывает он двух видов: split и overlay. На наши виджеты ложится почти один в один: split — это Row и Column, overlay — Stack. Разница в том, что ось выбираем не мы, а система, по форме и размеру доступного места.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VeUiqDAYqppK3QjxgzcIiA.png" /><figcaption><em>Split и overlay: Row и Column против Stack.</em></figcaption></figure><p>Что можно сделать уже сейчас, не дожидаясь устройства. Выкинуть из кода проверки ориентации. Собрать приложение под macOS и потаскать окно за угол: если при плавном изменении ширины что-то разъезжается, на Duo будет ровно то же самое. Перестать хардкодить отступы. И главное — не терять состояние при смене раскладки: раскрытие телефона это не переход на новый экран, а расширение текущего. Список и карточка просто встают рядом.</p><p>В этом, собственно, и вся мысль гайдлайнов. Меняется не структура приложения, а только то, как поделено место: 30/70 в раскрытом виде, 45/55 пока телефон складывают. Если приложение спокойно переживает любую ширину, Duo для него — просто ещё один размер окна.</p><p><em>Гайдлайны Apple: </em><a href="https://developer.apple.com/design/human-interface-guidelines/designing-for-iphone-duo"><em>https://developer.apple.com/design/human-interface-guidelines/designing-for-iphone-duo</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=122b80adf928" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Foldable iPhone and Flutter]]></title>
            <link>https://medium.com/@dinmukhammed.yerimbetov/foldable-iphone-and-flutter-it-just-works-isnt-our-story-1d62883d28a3?source=rss-1a6d95302e36------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d62883d28a3</guid>
            <dc:creator><![CDATA[Dimash Yerimbetov]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 19:29:44 GMT</pubDate>
            <atom:updated>2026-09-14T13:28:05.718Z</atom:updated>
            <content:encoded><![CDATA[<p>I went through Apple’s guidelines for adapting to the iPhone Duo and got that familiar feeling. The docs sound calm and reasonable: use system navigation, support window resizing, and most of the work takes care of itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Twz9v2SeWTyqp3_H.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F4V6Mx2xXsARt5o5.png" /><figcaption>Device poses</figcaption></figure><p>Then you remember you write Flutter.</p><p>As far as iOS is concerned, our app is one big UIView that we draw everything inside. All that system magic passes us by. NavigationSplitView that collapses into a single column and knows where the fold runs? Not ours. A sheet that slides away from the crease on its own? Ours will sit dead center, right on the fold, and stay there. A toolbar that moves to the side edge on the cover screen? Our AppBar stays exactly where it always was, on top.</p><p>You can also just do nothing. The app won’t break. It’s only that on the wide, short cover screen a bottom tab bar eats a third of the height, and the Send button ends up on the crease.</p><p>Orientation goes first. On the inner screen, iOS no longer looks at the orientations an app declares. Which means the familiar orientation == Orientation.landscape check doesn&#39;t really guarantee anything anymore. Layout decisions have to come from the actual window width: LayoutBuilder, breakpoints, and that&#39;s it.</p><p>There’s good news here, though. It’s the same discipline as proper iPad support. If you’ve already been through that, half the work is behind you.</p><p>Next comes the Reserved Region. On top of the usual safe area there are now zones you can’t put content into: two front cameras and the folding area in the middle. And the fold actually splits the screen into parts, while a camera simply covers a piece of it. Two different problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgOmdYf1cc5DEeoOmB3Y8g.png" /><figcaption><em>The panes stay the same, only their share of the screen changes. The hatched strip is where nothing interactive should land.</em></figcaption></figure><p>Flutter is partly ready for this. MediaQuery has had displayFeatures with fold and cutout types for a while, and DisplayFeatureSubScreen knows how to push dialogs to one side of the hinge. All of it was built for Android foldables, though. Whether Flutter picks up the new iOS API is anyone&#39;s guess. Until it does, it&#39;s a platform channel and a plugin of your own.</p><p>The heaviest part is the vertical controls. Apple moves navigation and the toolbar to the side edge, and this is nothing like “rotate the AppBar 90 degrees”. Back and Close at the top, the primary action below, then everything else. Doesn’t fit? It goes into the overflow, bottom to top, by priority. And when two apps sit side by side, the left and right bars aren’t the same, because the camera is only on the right. Our closest equivalent is NavigationRail, but the priority and overflow logic is all yours to write.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wVZGqnyfD7MqAkS8FhUaIA.png" /><figcaption><em>Left: what a Flutter app draws today. Right: what the guidelines ask for.</em></figcaption></figure><p>A few things from Apple’s own page that the secondhand write-ups skip.</p><p>Portrait on the inner display is the exception: there’s enough height there, so the bars stay horizontal, right where you’d expect them. Which means one app can end up with three different control layouts in a single session, and the transitions between them are supposed to be boring.</p><p>When two apps share the inner display, each puts its controls on its own outer edge: the left app on the left, the right app on the right. That’s tied to the hardware rather than to reading direction, so it stays on the same side in right-to-left languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MFDuPZZbn51_b35QqhsZpQ.png" /><figcaption><em>The two halves aren’t mirror images: the camera lives on the right.</em></figcaption></figure><p>The examples Apple picked are the most useful part of the page. Notes keeps a split view and simply adjusts the pane widths so both stay clearly visible as the device folds. Calculator skips bars entirely and takes the full width, which is fine for a screen that doesn’t scroll, as long as nothing collides with the Dynamic Island. Mail shows either the list or the message when closed and both when open, and the controls that belong to the list stay above the list instead of moving off to the edge.</p><p>There’s also a genuinely useful rule for when the toolbar and the tab bar don’t both fit. On a navigation-heavy screen, keep the tab bar and push toolbar actions into the overflow. That’s the default. On a task-focused screen, do the opposite: minimize the tab bar and keep the actions that finish the job. And since items overflow from the bottom up, anything you want kept in sight needs an explicit priority: Compose in Mail, New Note in Notes, anything carrying a badge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbZ5nCaef4q3_WobJX-cug.png" /><figcaption><em>Left, a navigation-focused screen. Right, a task-focused one.</em></figcaption></figure><p>Arrangement views come in two kinds, split and overlay, and the mental model translates easily. An HStack or VStack is a split arrangement, a ZStack is an overlay one. Row and Column versus Stack, basically, except the system picks the axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VeUiqDAYqppK3QjxgzcIiA.png" /><figcaption><em>Split and overlay: Row and Column versus Stack.</em></figcaption></figure><p>What’s worth doing right now, without waiting for the device: rip the orientation checks out, drag the window around in a macOS build and make sure nothing falls apart while the width changes smoothly, and stop hardcoding insets. Most importantly, don’t lose state when the layout changes. Unfolding isn’t a navigation event, it’s the current screen getting more room: the list and the detail simply end up next to each other, and the user stays exactly where they were.</p><p>That’s the whole idea behind the guidelines, really. The structure of the app doesn’t change, only how the space is divided: 30/70 fully open, 45/55 while folding. If your app takes any width in stride and forgets nothing along the way, Duo is just one more window size. If there’s still an if (isTablet) living somewhere inside, you&#39;re going to feel this phone. And by the looks of it, fairly soon.</p><p><em>Apple’s guidelines: </em><a href="https://developer.apple.com/design/human-interface-guidelines/designing-for-iphone-duo"><em>https://developer.apple.com/design/human-interface-guidelines/designing-for-iphone-duo</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d62883d28a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[So recently I tried to create that “beautiful”) Liquid Glass effect from iOS 26 in Flutter.]]></title>
            <link>https://medium.com/@dinmukhammed.yerimbetov/so-recently-i-tried-to-create-that-beautiful-liquid-glass-effect-from-ios-26-in-flutter-b3c07681f68f?source=rss-1a6d95302e36------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3c07681f68f</guid>
            <category><![CDATA[liquid-glass-ui]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[liquid-glass]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[apple-liquid-glass]]></category>
            <dc:creator><![CDATA[Dimash Yerimbetov]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 18:15:40 GMT</pubDate>
            <atom:updated>2025-06-26T18:25:48.159Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*VW6anOQQCldrgefPyxntEQ.png" /></figure><p>So recently I tried to create that “beautiful”) Liquid Glass effect from iOS 26 in Flutter. Turns out… It is quite hard to implement this exact effect 😅. But the good news? There are already plenty of open-source demos and clever packages out there, and by digging into them, I somehow understood what really goes into making this effect feel so magical.</p><p>If you’re like me and didn’t initially grasp the logic behind this effect, this post will give you an abstract overview of essential parts and what to search for to get the explanation behind it.</p><p>1. Transparent and Adaptive Colors<br>iOS 26 doesn’t just blur the background, it blends with it. UI elements are semi-transparent and react to what’s behind them in real-time. If your wallpaper is dark or colorful, buttons subtly shift to reflect that tone. The system dynamically samples colors and adjusts the tint to stay visually coherent.</p><p>How it works? — Real-time background texture sampling, color blending</p><p>2. Refraction Like Real Glass<br>Elements behave like actual thick glass. The content behind is bent, warped, and distorted, just like how light refracts through a lens.</p><p>How it works? — Screen-space coordinate distortion via Normal Map</p><p>3. Reflections and Environmental Highlights<br>These aren’t static shapes with transparency. They reflect. If your wallpaper has texture or bright areas, you’ll notice faint highlights mirrored on buttons or cards. And when you tilt your phone, those reflections shift ever so slightly.</p><p>How it works? — Simulated lighting model + environment map + real-time reflections</p><p>4. Fluid Motion and Morphing UI<br>Buttons compress when scrolling, chips stretch and float, and everything has this elastic, responsive behavior. Nothing feels flat or static.</p><p>How it works? — Physics-based animation, Metaballs/SDF Shape Blending</p><p>Final thoughts:<br>And while Flutter doesn’t (and probably won’t) support this style natively, packages like liquid_glass_renderer (<a href="https://pub.dev/packages/liquid_glass_renderer">https://pub.dev/packages/liquid_glass_renderer</a>) can get you pretty close. Although the final result might still fall slightly short of native-level realism, the visual fidelity is impressive overall. Hats off to the devs-pulling off this level of complexity takes real skill, and performance in tests looks solid too ❤‍🔥❤‍🔥❤‍🔥</p><p>It’s definitely a non-trivial shader, and without AI-assisted explanations, I probably wouldn’t have understood what each part does 🫠</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3c07681f68f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dart HashMap Deep Dive: Internals, Collisions, and Performance]]></title>
            <link>https://medium.com/@dinmukhammed.yerimbetov/dart-hashmap-deep-dive-internals-collisions-and-performance-5dcfbddfd403?source=rss-1a6d95302e36------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dcfbddfd403</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[collections-in-dart]]></category>
            <category><![CDATA[hashmap]]></category>
            <category><![CDATA[dartlang]]></category>
            <dc:creator><![CDATA[Dimash Yerimbetov]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 00:27:20 GMT</pubDate>
            <atom:updated>2025-03-17T06:01:45.050Z</atom:updated>
            <content:encoded><![CDATA[<p>HashMaps are essential data structures. They’re fast, efficient, and incredibly useful for quick key-value lookups. But do you really know how they work under the hood, especially in Dart?</p><p>Understanding the internal mechanics of Dart’s HashMap isn’t just theory — it directly impacts your application’s performance and reliability. Poor implementations or misconceptions about hashing and equality (==) can lead to <strong>slowdowns</strong>, unnecessary <strong>memory usage</strong>, and hard-to-detect <strong>memory leaks</strong>.</p><p>In this post, we’ll explore Dart’s HashMap implementation by dissecting its source code, explaining key concepts like <strong>buckets</strong>, <strong>collisions</strong>, and discussing best practices for optimal performance.</p><h3><strong>How HashMap Works Internally</strong></h3><p>Let’s deep dive into the <strong>Dart SDK source code</strong> to understand how HashMap works. Specifically, let’s check the file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*TxAl_59I5b7PFZGmRWzAgA.png" /></figure><p>Internally, Dart’s HashMap uses a data structure known as a <strong>bucket array</strong>:</p><pre>base class _HashMap&lt;K, V&gt; extends MapBase&lt;K, V&gt; implements HashMap&lt;K, V&gt; {<br>  static const int _INITIAL_CAPACITY = 8;<br><br>  int _elementCount = 0;<br>  var _buckets = List&lt;_HashMapEntry?&gt;.filled(_INITIAL_CAPACITY, null);<br>  int _modificationCount = 0;<br><br>  ...<br>}</pre><p>Each bucket is a slot in a fixed-length list (List), initially with 8 buckets (_INITIAL_CAPACITY = 8). Every bucket can store multiple elements via a linked list structure called _HashMapEntry:</p><pre>class _HashMapEntry {<br>  final Object? key;<br>  Object? value;<br>  final int hashCode;<br>  _HashMapEntry? next;<br>  _HashMapEntry(this.key, this.value, this.hashCode, this.next);<br>}</pre><h4><strong>Storing and Retrieving Values</strong></h4><p>When you store or retrieve values in a HashMap, two operations happen internally — <strong>Bucket Index Calculation and Handling Collisions (Separate Chaining)</strong></p><ol><li><strong>Storing operation (operator []=):</strong></li></ol><pre>void operator []=(K key, V value) {<br>  final hashCode = key.hashCode;<br>  final buckets = _buckets;<br>  final length = buckets.length;<br>  final index = hashCode &amp; (length - 1);<br>  var entry = buckets[index];<br>  while (entry != null) {<br>    if (hashCode == entry.hashCode &amp;&amp; entry.key == key) {<br>      entry.value = value;<br>      return;<br>    }<br>    entry = entry.next;<br>  }<br>  _addEntry(buckets, index, length, key, value, hashCode);<br>}</pre><p><strong>2. Lookup operation (operator []):</strong></p><pre>V? operator [](Object? key) {<br>  final hashCode = key.hashCode;<br>  final buckets = _buckets;<br>  final index = hashCode &amp; (buckets.length - 1);<br>  var entry = buckets[index];<br>  while (entry != null) {<br>    if (hashCode == entry.hashCode &amp;&amp; entry.key == key) {<br>      return unsafeCast&lt;V&gt;(entry.value);<br>    }<br>    entry = entry.next;<br>  }<br>  return null;<br>}</pre><p>As you see in both of them Dart calculates the bucket index with a <strong>bitwise AND (&amp;)</strong> operation. And after that, checks for a <strong>collision case </strong>when multiple keys map to the same bucket. Dart resolves collisions with a <strong>linked list (chaining).</strong></p><p>Time complexity of <strong>[]= and [] operations</strong>: <br>• average: O(1), <br>• worst (collision-heavy): O(n)</p><h4><strong>Visualization:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/0*8ijkDpjQ6oJ2CAj-.png" /><figcaption>This image illustrates <strong>how hash tables works and handles collision</strong>:</figcaption></figure><p>Initially, there’s an <strong>empty hash table</strong> with 7 buckets (0–6). As numbers are inserted:</p><p>• <strong>Insert 50</strong>: placed in bucket 1 (no collision).<br>• <strong>Insert 700 and 76</strong>: 700 goes to bucket 0, and 76 to bucket 6 (no collision yet).<br>• <strong>Insert 85</strong>: collision occurs at bucket 1 (already contains 50). It’s added to a linked list in bucket 1.<br>• <strong>Insert 92</strong>: another collision at bucket 1 (contains 50 and 85 already). 92 is appended at the end of the linked list.</p><h4>Why <strong>50, 85 and 92 </strong>ends up in the same bucket?</h4><p>To find a bucket index, hash tables commonly use this calculation:<br><strong><em>bucket index = key.hashCode % number_of_buckets</em></strong></p><p>50 % 7 = 1<br>85 % 7 = 1<br>92 % 7 = 1</p><p>This is precisely why collisions occur — multiple distinct keys produce the same bucket index. To handle this, the hash table uses separate chaining (linked lists), allowing multiple elements to share a bucket.</p><p>Dart uses bitwise AND operation to calculate index. <br><strong><em>bucket index = key.hashCode &amp; (number_of_buckets — 1)</em></strong></p><p><strong>Why bitwise? </strong>Because<strong> </strong>a bitwise AND (&amp;) operation is faster than modulo (%). This operation is efficient. Dart maintains bucket arrays with sizes that are always powers of two.</p><blockquote><strong>Fun Fact: </strong>Bitwise AND can sometimes act like a modulus for powers of 2.<strong> </strong>If x is a positive integer and y is a power of 2, then:</blockquote><blockquote><em>x % y == x &amp; (y — 1)</em></blockquote><blockquote><em>For example:</em></blockquote><blockquote>int mod = 13 % 8; // is 5<br>int bitwise = 13 &amp; (8–1); // is also 5</blockquote><blockquote>Bitwise is an <strong>efficient trick</strong> used in low-level optimizations.</blockquote><h4><strong>What is a Hash Collision?</strong></h4><p>A collision happens when different keys have the same bucket index. Here’s an example:</p><pre>import &#39;dart:collection&#39;;<br><br>void main() {<br> var map = HashMap&lt;int, String&gt;();<br><br> int key1 = 5; // hashCode → 5<br> int key2 = 21; // hashCode → 21<br> <br> // Assuming bucket length = 16:<br> print(key1.hashCode &amp; 15); // 5, Result in binary 101<br> print(key2.hashCode &amp; 15); // 5, Result in binary 101 <br><br> // final bucketIndex = hashCode &amp; (bucketLength - 1);<br> map[key1] = &quot;First&quot;; // bucketIndex is 5<br> map[key2] = &quot;Second&quot;; // bucketIndex is 5 (collision occurs!)<br><br> print(map[key1]); // &quot;First&quot;<br> print(map[key2]); // &quot;Second&quot; Time Complexity O(n) =(<br>}</pre><p>Both keys go into bucket #5, forming a linked list:</p><pre>/// List _buckets<br>/// [<br>///  ...<br>///  #3 null,<br>///  #4 null,<br>///  #5 _HashMapEntry(key1, &quot;First&quot;, hash1) -&gt; _HashMapEntry(key2, &quot;Second&quot;, hash2) -&gt; null<br>///  #6 null,<br>///  ...<br>/// ]</pre><p>Collisions are problematic because they negatively affect the performance. Specifically, when collisions occur, multiple keys end up in the same bucket, requiring the structure to scan through a linked list to find the correct key-value pair.</p><p>Without collisions, HashMap operations like insertions, deletions, and lookups have an ideal <strong>time complexity of O(1)</strong> — constant time. However, if many collisions happen (meaning many keys share the same bucket), the structure degrades into a linked list, causing operations to slow down to <strong>O(n)</strong> — linear time complexity.</p><h4><strong>When Does a HashMap Resize?</strong></h4><p>Dart automatically resizes (doubles the bucket array) when more than 75% of buckets are occupied:</p><pre>void _addEntry(List&lt;_HashMapEntry?&gt; buckets, int index, int length, K key, V value, int hashCode) {<br>  final entry = new _HashMapEntry(key, value, hashCode, buckets[index]);<br>  buckets[index] = entry;<br>  final newElements = _elementCount + 1;<br>  _elementCount = newElements;<br>  // If we end up with more than 75% non-empty entries, we<br>  // resize the backing store.<br>  if ((newElements &lt;&lt; 2) &gt; ((length &lt;&lt; 1) + length)) _resize();<br>  _modificationCount = (_modificationCount + 1) &amp; _MODIFICATION_COUNT_MASK;<br>}</pre><p>Resizing doubles the bucket size to maintain performance:<br>• Creates a new bucket array double the old length.<br>• Rehashes all entries into the new buckets.</p><p><strong>Load Factor Awareness: </strong>While Dart automatically manages resizing, manually keeping the HashMap with a suitable initial capacity can reduce resize overhead.</p><h3><strong>Why Proper hashCode and == in Objects are Essential for HashMaps</strong></h3><p>In Dart, when you use custom objects as keys in collections like HashMap or elements in sets (HashSet), correctly implementing the hashCode and == operator is crucial for performance.</p><pre>while (entry != null) {<br>  /// uses implementation of hashCode and equality check of a key<br>  if (hashCode == entry.hashCode &amp;&amp; entry.key == key) {<br>    return unsafeCast&lt;V&gt;(entry.value);<br>  }<br>  entry = entry.next;<br>}</pre><p>Both <strong>lookup ([])</strong> and <strong>insertion ([]=) </strong>and many other<strong> </strong>operations in a HashMap rely on these implementations (hashCode and equality check), as shown in the code above. If they are incorrect, it can lead to serious problems.</p><p>Hash codes by design must be the same for objects that are equal to each other according to <a href="https://api.flutter.dev/flutter/dart-core/Object/operator_equals.html">operator ==</a>. The hash code of an object should only change if the object changes in a way that affects equality. There are no further requirements for the hash codes.</p><p><strong>Example of a Bad Implementation:</strong></p><pre>import &#39;dart:collection&#39;;<br><br>class Person {<br>  final String name;<br>  final int age;<br><br>  Person(this.name, this.age);<br><br>  // Bad implementation: Only name considered<br>  @override<br>  int get hashCode =&gt; name.hashCode;<br><br>  // Equality checks both name and age<br>  @override<br>  bool operator ==(Object other) =&gt; other is Person &amp;&amp; name == other.name &amp;&amp; age == other.age;<br>}<br><br>void main() {<br>  final personMap = HashMap&lt;Person, String&gt;();<br><br>  final person1 = Person(&#39;Alice&#39;, 30);<br>  final person2 = Person(&#39;Alice&#39;, 25); // same name, different age<br><br>  personMap[person1] = &#39;Engineer&#39;;<br>  personMap[person2] = &#39;Designer&#39;;<br><br>  print(personMap[person2]); // Lookup time is O(n) =(<br>}</pre><p>Because hashCode doesn’t align with equality (==), two different objects will be located in the same bucket in a HashMap.</p><h3>Common Pitfalls in Dart Hashing: How to Avoid Collisions and Improve Performance</h3><h4><strong>Problem 1: Mutable Objects as Key</strong></h4><p>Changing the hashCode of a key <strong>after inserting it into a HashMap</strong> can cause serious issues. Example scenario:</p><pre>class MutableKey {<br>  int id;<br><br>  MutableKey(this.id);<br><br>  @override<br>  int get hashCode =&gt; id;<br><br>  @override<br>  bool operator ==(Object other) =&gt; other is MutableKey &amp;&amp; id == other.id;<br>}<br><br>void main() {<br>  var map = HashMap&lt;MutableKey, String&gt;();<br><br>  final key = MutableKey(10);<br>  map[key] = &quot;Mutable Value&quot;;<br><br>  print(map[key]); // &quot;Mutable Value&quot;<br>  key.id = 20; // Mutating the key after insertion:<br>  print(map[key]); // null (value becomes unreachable)<br>}</pre><p>Once mutated, the lookup index changes and the key becomes invalid for lookup, causing a <strong>memory leak</strong>.</p><p>If you still need to have mutable objects as a key, then consider using HashMap.identity(). It ignores any overridden hashCode and equality operator of an Object:</p><pre>base class _IdentityHashMap&lt;K, V&gt; extends _HashMap&lt;K, V&gt; {<br>  ...<br>  V? operator [](Object? key) {<br>    final hashCode = identityHashCode(key); /// get original hashCode<br>    final buckets = _buckets;<br>    final index = hashCode &amp; (buckets.length - 1);<br>    var entry = buckets[index];<br>    while (entry != null) {<br>      /// checks with original hashCodes &amp;&amp; checks with identical()<br>      if (hashCode == entry.hashCode &amp;&amp; identical(entry.key, key)) {<br>        return unsafeCast&lt;V&gt;(entry.value);<br>      }<br>      entry = entry.next;<br>    }<br>    return null;<br>  }<br>  ...<br>}</pre><p>IdentityHashMap (created using HashMap.identity()) is a <strong>special type of HashMap</strong> that uses <strong><em>identityHashCode()</em></strong> and<strong><em> identical(</em></strong>) which compares keys based on <strong>object identity (memory address)</strong> rather than the usual == operator.</p><pre>/// The identity hash code of [object].<br>///<br>/// Returns the value that the original [Object.hashCode] would return<br>/// on this object, even if `hashCode` has been overridden.<br>///<br>/// This hash code is compatible with [identical],<br>/// which means that it&#39;s guaranteed to give the same result every time<br>/// it&#39;s passed the same argument, throughout a single program execution,<br>/// for any *non-record* object.<br>@pragma(&quot;vm:entry-point&quot;)<br>external int identityHashCode(Object? object);</pre><h4><strong>Problem 2: Objects with </strong>straightforward hashCode <strong>as key</strong></h4><p>Default hash functions (combining fields naively) lead to frequent collisions. Solution is to use Dart’s built-in Object.hash():</p><pre>class CompositeObject {<br>  final String name;<br>  final int id;<br>  final bool isActive;<br><br>  CompositeObject(this.name, this.id, this.isActive);<br> <br>  // Bad! straightforward, naively<br>  // @override<br>  // int get hashCode =&gt; name.hashCode + id + isActive.hashCode;<br><br>  // Good! proper hashing strategy<br>  @override<br>  int get hashCode =&gt; Object.hash(name, id, isActive);<br><br>  @override<br>  bool operator ==(Object other) =&gt;<br>      other is CompositeObject &amp;&amp;<br>      name == other.name &amp;&amp;<br>      id == other.id &amp;&amp;<br>      isActive == other.isActive;<br>}<br><br>// Usage:<br>void main() {<br>  final map = &lt;CompositeObject, String&gt;{};<br><br>  final obj = CompositeObject(&#39;Alice&#39;, 123, true);<br>  map[obj] = &#39;Data&#39;;<br><br>  print(map[obj]); // fast and reliable lookups<br>}</pre><h4><strong>Problem 3: Floating-Point Numbers as key</strong></h4><p><strong>Issue:</strong> Floating-point precision errors cause hash inconsistencies.</p><blockquote>Computers store floating-point numbers (like double or float) as binary fractions. Many decimal numbers cannot be represented precisely in binary. This limitation leads to subtle errors or inaccuracies.The number 0.1 in decimal cannot be exactly represented as a binary fraction — it’s a repeating number in binary. Thus, arithmetic operations on floats often produce slightly inaccurate results.</blockquote><p><strong>Why is this problematic in HashMaps?</strong></p><p>When using floating-point numbers as keys in hash-based structures:<br>• Slight inaccuracies lead to different hash values.<br>• Equal numbers (visually) might produce different hashes.</p><pre>import &#39;dart:collection&#39;;<br><br>void main() {<br>  final map = &lt;double, String&gt;{};<br>  map[0.3] = &#39;Value for 0.3&#39;;<br>  print(map[0.1 + 0.2]); // prints &quot;null&quot; instead of &quot;Value for 0.3&quot;<br>}</pre><p>Due to floating-point precision, 0.1 + 0.2 equals 0.30000000000000004, not exactly 0.3. This means the lookup fails, returning null.</p><p><strong>Recommended Solution: <br></strong>Use a <strong>custom wrapper class</strong> with fixed-point representation:</p><pre>import &#39;dart:collection&#39;;<br><br>class FixedDouble {<br>  final double value;<br><br>  FixedDouble(this.value);<br><br>  @override<br>  bool operator ==(Object other) =&gt;<br>      other is FixedDouble &amp;&amp; (value - other.value).abs() &lt; 0.00001;<br><br>  @override<br>  int get hashCode =&gt; fixedHashCode(value);<br>}<br><br>int fixedHashCode(double value, [int precision = 10000]) {<br>   return (value * precision).toInt();<br>}<br><br>void main() {<br>  final map = HashMap&lt;FixedDouble, String&gt;();<br>  map[FixedDouble(0.3)] = &#39;Value for 0.3&#39;;<br>  print(map[FixedDouble(0.1 + 0.2)]); // reliably prints &quot;Value for 0.3&quot;<br>}</pre><p>This solution provides consistent behavior and avoids pitfalls caused by floating-point precision errors.</p><h4><strong>Problem 4:</strong> <strong>Using Heavy Objects as key</strong></h4><p>When using very large (“heavy”) objects — such as objects containing large file bytes, images, or extensive data — as keys in Dart collections, you may face serious performance issues.</p><p>This happens because Dart’s collections rely heavily on the hashCode and == operators. When these operators perform comparisons on large datasets (like byte arrays), performance quickly degrades and might freeze your main thread.</p><pre>class HeavyObject {<br>  final List&lt;int&gt; bytes;<br><br>  HeavyObject(this.bytes);<br><br>  @override<br>  int get hashCode =&gt; Object.hashAll(bytes);<br><br>  @override<br>  bool operator ==(Object other) =&gt;<br>      other is HeavyFile &amp;&amp; _areBytesEqual(other.bytes);<br><br>  bool _areBytesEqual(List&lt;int&gt; otherBytes) {<br>    if (bytes.length != otherBytes.length) return false;<br>    for (int i = 0; i &lt; bytes.length; i++) {<br>      if (bytes[i] != otherBytes[i]) return false;<br>    }<br>    return true;<br>  }<br>}</pre><p>Each equality check (==) involves potentially comparing millions of bytes, drastically slowing down your application.</p><p><strong>Recommended Solution: </strong>The best practice is to avoid heavy comparisons by hashing a lightweight representation — usually a <strong>unique ID or checksum</strong> (e.g., SHA256 hash of file contents).</p><pre>import &#39;dart:convert&#39;;<br>import &#39;package:crypto/crypto.dart&#39;;<br><br>class HeavyObjectOptimized {<br>  final List&lt;int&gt; bytes;<br>  final String _checksum;<br><br>  HeavyObjectOptimized(this.bytes)<br>      : _checksum = sha256.convert(bytes).toString();<br><br>  @override<br>  int get hashCode =&gt; _checksum.hashCode;<br><br>  @override<br>  bool operator ==(Object other) =&gt; other is HeavyFileOptimized &amp;&amp; _checksum == other._checksum;<br>}<br><br>void main() {<br>  final map = &lt;HeavyFileOptimized, String&gt;{};<br><br>  final file1 = HeavyFileOptimized([1, 2, 3, ...]); // large file bytes<br>  final file2 = HeavyFileOptimized([1, 2, 3, ...]); // identical large file<br><br>  map[file1] = &#39;File 1 Data&#39;;<br>  print(map[file2]); // reliable lookup<br>}</pre><blockquote>It’s generally <strong>not a good practice</strong> to use heavy objects — such as objects containing extensive data — as keys in maps or sets in Dart.</blockquote><h3><strong>Conclusion: Understanding HashMaps as a Core Abstraction in Dart &amp; Flutter</strong></h3><p>The design of a HashMaps reflects a fundamental principle from computer science — the careful balancing of efficiency, predictability, and performance. This powerful design philosophy not only results in highly performant key-value storage but also equips developers with flexible and robust solutions to tackle complex application challenges. Proper hash design transforms seemingly chaotic data into structured, easily accessible information, dynamically balancing memory usage and computational cost.</p><p>In <strong>Flutter development</strong>, HashMaps isn’t merely a <strong>data container</strong> — it underpins crucial application architectures like <strong>state management</strong>, <strong>routing configurations</strong>, and <strong>caching systems</strong>.</p><p>Mastering the subtleties and internals of Dart HashMaps positions you to make smarter decisions in performance optimization and architectural design, enabling you to solve challenging development problems clearly and effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dcfbddfd403" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Myth-Busting: Will one million setState calls slow your app down?]]></title>
            <link>https://medium.com/@dinmukhammed.yerimbetov/flutter-myth-busting-will-one-million-setstate-calls-slow-your-app-down-8d85208dd5f1?source=rss-1a6d95302e36------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d85208dd5f1</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Dimash Yerimbetov]]></dc:creator>
            <pubDate>Sat, 08 Mar 2025 18:48:23 GMT</pubDate>
            <atom:updated>2025-03-08T18:48:23.469Z</atom:updated>
            <content:encoded><![CDATA[<p>I bet almost every Flutter developer worried at least once that calling setState too frequently might slow down your Flutter app. Let’s see what really happens when we call setState ONE MILLION TIMES back-to-back!</p><p>Here’s the madness in code form for simple Counter app 🤡:</p><pre>// Extreme Increment!<br>void _setState1000000() {<br> for (int i = 0; i &lt; 1000000; i++) {<br> setState(() =&gt; _counter++);<br> }<br>}</pre><p>If we check Flutter’s profiler after calling _setState1000000(), we’ll discover that everything remains smooth! Even after one million setState calls, Flutter does NOT rebuild the UI one million times. Instead, it triggers only one rebuild per frame!</p><p>When you call setState, Flutter marks the widget as “dirty” (needs rebuild). If you call it again before the next frame, Flutter sees it’s already dirty and does nothing extra.</p><p>Check out Flutter’s internal logic 🤔:</p><pre>void markNeedsBuild() {<br> if (dirty) return; // Already marked dirty? Do nothing.<br> _dirty = true;<br> owner!.scheduleBuildFor(this);<br>}</pre><p>Inside owner.scheduleBuildFor(this), Flutter gathers widgets that need rebuilding and schedules the next frame update. Since the widget is marked dirty only once, even if setState is called 1,000,000 times, it is added to the rebuild queue only once, resulting in just one frame update.</p><p>This tiny check is what allows Flutter to effortlessly handle massive amounts of state updates! It automatically batches UI updates, preventing unnecessary rebuilds. Calling setState multiple times won’t overload your UI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d85208dd5f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding pub get, pub upgrade, and pubspec.lock in Flutter]]></title>
            <link>https://medium.com/@dinmukhammed.yerimbetov/understanding-pub-get-pub-upgrade-and-pubspec-lock-in-flutter-d4bc2c0bead1?source=rss-1a6d95302e36------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4bc2c0bead1</guid>
            <category><![CDATA[pubspec]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[dartlang]]></category>
            <dc:creator><![CDATA[Dimash Yerimbetov]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 22:13:51 GMT</pubDate>
            <atom:updated>2025-02-28T22:13:51.751Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the common confusions among Flutter developers i face is how pub’s dependency management works, especially the difference between pub get and pub upgrade, and the role of pubspec.lock. Let’s break it down.</p><p>To avoid dependency conflict errors, we must understand these three things perfectly — pub get, pub upgrade and the role of pubspec.lock</p><p><strong>❗ pub get<br></strong>• Fetches dependencies specified in pubspec.yaml, but prioritizes versions already locked in pubspec.lock and cached in .pub-cache.<br>• If nothing changes in pubspec.yaml, it won’t fetch newer versions from remote sources.</p><p><strong>❗ pub upgrade<br></strong>• Forces an update to the latest versions of dependencies allowed by pubspec.yaml. <br>• Semantic cases when it can upgrade dependencies: ‘&gt;=x.y.z &lt;a.b.c’ or ^x.y.z<br>• It can cause API changes and compilation issues.</p><p><strong>❗ The role of pubspec.lock<br></strong>• This file ensures that all developers on a team use the same dependency versions. <br>• It locks specific versions after pub get. Once you’ve got a lockfile for your app, pub won’t touch it until you tell it to. Once your app is locked, it stays locked until you manually tell it to update the lockfile.<br>• If pubspec.lock is not committed, different developers might get different versions, leading to inconsistency and potential errors.</p><h3>⚠ Recommendations</h3><p>✔ Avoid using pub upgrade carelessly. If you’re working in a team, always track pubspec.lock to prevent version conflicts. It’s better to lock dependency versions when stability is more important than new features.</p><p>✔ Commit pubspec.lock, but do it only for application packages to ensure that all developers on a team use the same dependency versions. When checking the Dart official documentation under “What not to commit” (<a href="https://dart.dev/tools/pub/private-files">https://dart.dev/tools/pub/private-files</a>), we find that it is not recommended to commit the pubspec.lock file for libraries in source code repositories. The reason is that libraries should support a range of dependency versions, allowing flexibility while ensuring compatibility with tested versions.</p><p>✔ When multiple dependencies are involved, try to use the ^ symbol or range of versions. Depending on single concrete versions lacks flexibility. Coupled with shared dependencies, it leads to version lock. To cope with version lock, your package should depend on a range of versions. Once your app has a solid set of versions for its dependencies, that set gets pinned down in a lockfile. That ensures that every machine running your app uses the same versions of all of its dependencies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4bc2c0bead1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complex Animations in Flutter: Creating a Dynamic Circular Water-Ripple Progress Bar]]></title>
            <link>https://medium.com/@dinmukhammed.yerimbetov/complex-animations-in-flutter-creating-a-dynamic-circular-water-ripple-progress-bar-c09175981f23?source=rss-1a6d95302e36------2</link>
            <guid isPermaLink="false">https://medium.com/p/c09175981f23</guid>
            <dc:creator><![CDATA[Dimash Yerimbetov]]></dc:creator>
            <pubDate>Thu, 12 Dec 2024 11:33:33 GMT</pubDate>
            <atom:updated>2024-12-12T11:33:33.225Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve come across some mesmerizing circular water-ripple animations on <a href="https://codepen.io/ElaineXu/pen/jrzGrw">CodePen</a> and was inspired to try implementing a similar effect in Flutter. By leveraging Flutter’s Canvas and CustomPainter classes, we can create a smooth, sine-wave-based progress indicator that stands out from traditional, static progress bars. The final result looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HgXJmrnu9FrTwW8jOpacHg.gif" /></figure><p>The core idea is straightforward:</p><ol><li>Draw a circle to represent the progress indicator.</li><li>Draw progress text or a percentage in the center.</li><li>Implement a moving wave animation inside the circle that corresponds to the current progress level.</li></ol><p>Before diving into drawing the wave and animating the progress, we first need to set up our animation controllers. These controllers handle both the wave’s horizontal movement and the progress indicator’s vertical fill level. In initState(), we’ll create and configure separate animation controllers — one for the progress itself, and another for the wave oscillation. By applying tweens and calling repeat() on the wave controller, we ensure that the animation runs continuously, allowing the wave to shift back and forth inside the circle.</p><pre>class _CircularWaveProgressState extends State&lt;CircularWaveProgress&gt; with TickerProviderStateMixin {<br>  late final AnimationController _progressController;<br>  late final AnimationController _waveController;<br>  late final Animation&lt;double&gt; _progressAnimation;<br>  late final Animation&lt;double&gt; _waveAnimation;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _progressController = AnimationController(vsync: this, duration: const Duration(seconds: 5));<br>    _waveController = AnimationController(vsync: this, duration: const Duration(seconds: 5));<br><br>    /// to speed up the wave animation, increase tween range<br>    _waveAnimation = Tween(begin: 0.0, end: 10.0).animate(_waveController);<br>    _progressAnimation = Tween(begin: 0.0, end: 100.0).animate(_progressController);<br><br>    _waveController.repeat();<br>  }<br>...<br>}</pre><p>We’ll use two painters: one for the animated wave inside the circle, and one for the progress arc and text overlaid on top, <strong>ProgressPainter </strong>and <strong>WavePainter</strong>.</p><pre>@override<br>Widget build(BuildContext context) {<br>  return CustomPaint(<br>    painter: WavePainter(<br>      progress: _progress,<br>      waveAnimation: _waveAnimation,<br>      circleRadius: sphereRadius,<br>    ),<br>    foregroundPainter: ProgressPainter(<br>      progress: _progress,<br>      circleRadius: sphereRadius,<br>    ),<br>  );<br>}</pre><blockquote>Note that you can tie the animation to your CustomPainter by providing the animations to its repaint parameter, as both progressAnimation and waveAnimation implement Listenable. This ensures that every frame of the animation triggers a repaint, keeping the visual output in sync with the animation’s state changes.</blockquote><pre>WavePainter({<br>  required this.progressAnimation,<br>  required this.waveAnimation,<br>  required this.circleRadius,<br>}) : super(repaint: Listenable.merge([progressAnimation, waveAnimation]));</pre><h3><strong>ProgressPainter</strong></h3><p>Let’s first establish the foundation of our circular progress bar. In the paint() method, we translate the canvas to the center and then handle two main drawing tasks _drawCircleProgress and _drawProgressText:</p><pre>@override<br>void paint(Canvas canvas, Size size) {<br>  final center = Offset(size.width / 2, size.height / 2);<br>  canvas.translate(center.dx, center.dy);<br><br>  _drawCircleProgress(canvas);<br>  _drawProgressText(canvas);<br>}</pre><p>To ensure our progress arc visualizes the correct portion of the circle, we rely on a few key formulas:</p><p><strong>Start Angle:</strong> We begin drawing from the top of the circle by using a start angle of -0.5 * π. In radians, this corresponds to the circle’s upper midpoint, so the arc grows clockwise from the top:</p><p><strong><em>startAngle = -0.5 * pi</em></strong></p><p><strong>Sweep Angle:</strong> The length of the arc corresponds to the current progress percentage. Since a full circle is 2 * π radians, the sweep angle for a given progress p (from 0 to 100) can be calculated as:</p><p><strong><em>sweepAngle = 2 * pi * (progress.value / 100)</em></strong></p><pre>/// Draws the circular progress with arc.<br>void _drawCircleProgress(Canvas canvas) {<br>  Paint circlePaint = Paint()<br>    ..color = circleBgColor<br>    ..strokeWidth = circleStrokeWidth<br>    ..style = PaintingStyle.stroke<br>    ..isAntiAlias = true;<br><br>  canvas.drawCircle(<br>    Offset.zero,<br>    circleRadius,<br>    circlePaint,<br>  );<br><br>  circlePaint<br>    ..color = circleProgressColor<br>    ..strokeCap = StrokeCap.round;<br><br>  canvas.drawArc(<br>    Rect.fromCircle(center: Offset.zero, radius: circleRadius),<br>    -0.5 * pi, // start angle<br>    2 * pi * (progress.value / 100), // sweep angle<br>    false,<br>    circlePaint,<br>  );<br>}</pre><blockquote>Take into accounts that when using Path.arcTo() to draw a complete circle arc (2 * π), it’s considered a zero-length path and thus won’t be rendered. For example, if you start at angle 0 and sweep through 2π, you’ll find that nothing is drawn. But if you change it to 2π — 1, suddenly it works. So that’s why it is better to draw with canvas.drawArc.</blockquote><p>For the progress percentage just translate progress.value to the textPainter:</p><pre>/// Draws the progress text.<br>void _drawProgressText(Canvas canvas) {<br>  final textSpan = TextSpan(<br>    text: &quot;${(progress.value).toInt()}%&quot;,<br>    style: const TextStyle(<br>      color: progressTextColor,<br>      fontSize: progressTextSize,<br>    ),<br>  );<br><br>  final textPainter = TextPainter(<br>    text: textSpan,<br>    textDirection: TextDirection.ltr,<br>  )..layout();<br><br>  textPainter.paint(<br>    canvas,<br>    Offset(-textPainter.width / 2, -textPainter.height / 2),<br>  );<br>}</pre><p>The final result looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NIOQLV4arAcdoUES7vhrWg.gif" /></figure><p>Implement a moving wave animation inside the circle that corresponds to the current progress level.</p><h3>WavePainter</h3><p>This section focuses on drawing dynamic, layered sine waves inside a circular area, creating the illusion of rippling water beneath the progress arc.</p><p><strong>Sine Functions for Periodic Curves</strong></p><p>Sine waves are a perfect fit for simulating the natural up-and-down motion of water. For better understanding try to read this article <a href="https://mathematicalmysteries.org/sine-wave/">https://mathematicalmysteries.org/sine-wave/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*8SVl621GCYAhSlG3E5BZFw.gif" /></figure><p>The general sine function looks like this: <strong><em>y = A * sin(ωx + φ) + k</em></strong></p><ul><li><strong>A (Amplitude):</strong> Determines the wave’s height.</li><li><strong>ω (Angular frequency):</strong> Controls how rapidly the wave oscillates along the x-axis, affecting the wavelength.</li><li><strong>φ (Phase shift):</strong> Moves the wave along the x-axis, useful for creating the feeling of motion. In our case it is <strong>offsetX</strong></li><li><strong>k (Vertical shift):</strong> Moves the entire wave up or down on the y-axis. In our case it is <strong>offsetY</strong></li></ul><p>By adjusting these parameters, we can draw a path that looks like a wave:</p><pre>double amplitude = 15.0;<br>double angularVelocity = pi / circleRadius;<br><br>double offsetX = 2 * circleRadius * waveAnimation.value;<br>double offsetY = startY + (endY - startY - amplitude) * progress.value / 100;<br><br>Path path = Path();<br><br>for (double x = startX; x &lt;= endX; x++) {<br>  /// y = A * sin(ωx + φ) + k wave function itself, where A is amplitude, ω is angular velocity, φ is phase shift(x)<br>  double y = amplitude * sin(angularVelocity * (x + offsetX)) + offsetY;<br>  if (x == startX) {<br>    path.moveTo(x, y);<br>  } else {<br>    path.lineTo(x, y);<br>  }<br>}</pre><p>After plotting the sine wave line from startX to endX, these final commands close the shape, forming a filled area that looks like a body of water.</p><pre>path.lineTo(endX, startY);<br>path.lineTo(startX, startY);<br>path.close();</pre><p>The result will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*C3o6OaG727t6wXUHDWDMqA.gif" /></figure><p>Let’s put it all together and see what the final outcome looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*Cn-3H_31Wv3TSoci7LNu7Q.gif" /></figure><p>Finally, we clip the wave canvas to a circular path. This ensures that the flowing waves remain neatly contained within the circle’s boundary, adding the perfect finishing touch to our animated water effect.</p><pre>canvas.clipPath(<br>  Path()<br>    ..addOval(<br>      Rect.fromCircle(<br>        center: Offset.zero,<br>        radius: circleRadius,<br>      ),<br>    ),<br>);</pre><p>To enhance realism, we can apply a Curves.slowMiddle transformation to vertical shift with the progress value. By doing this, the water appears to fill more gradually and naturally in the center of the sphere, since there is more space in the center and it takes more time to fill it there:</p><pre>double delta = Curves.slowMiddle.transform(progress.value / 100);<br>double offsetY = startY + (endY - startY - amplitude) * delta;</pre><p><strong>Final result will look like this:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*mWNpkLVXXsqITsfO74_ITQ.gif" /></figure><h3><strong>Conclusion</strong></h3><p>With this approach, we’ve built a versatile and visually captivating circular water-ripple progress bar. Starting from clipping the canvas, layering sine waves, and fine-tuning animation curves, we’ve managed to create a fluid, organic effect that feels far more engaging than a standard progress indicator.</p><p>Feel free to experiment further — try adding a second wave in the background for more depth, introduce subtle shadows for enhanced realism, or tweak the amplitude and frequency of the sine waves to match your preferred style</p><p>For the complete source code and further experimentation, check out the repository here: <a href="https://github.com/meeziest/spherical_water_wavy_progress_bar">GitHub Link</a>. Enjoy exploring and refining this effect!</p><p>If you’re interested in more tips, tricks, and discussions on Dart and Flutter, be sure to join my Telegram channel: <a href="https://t.me/dart_flutter_with_mizu">Dart &amp; Flutter with Mizu</a>. It’s a great place to learn, share, and stay inspired.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c09175981f23" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>