<?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 Oleksii Bukhantsov on Medium]]></title>
        <description><![CDATA[Stories by Oleksii Bukhantsov on Medium]]></description>
        <link>https://medium.com/@oleksiibukhantsov?source=rss-3830bbfa6692------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*02M-i1XCmzcvqEQ9.</url>
            <title>Stories by Oleksii Bukhantsov on Medium</title>
            <link>https://medium.com/@oleksiibukhantsov?source=rss-3830bbfa6692------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 03:51:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oleksiibukhantsov/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[Interactive Graph from scratch in Flutter: Physics, Animations, and CustomPainter]]></title>
            <link>https://medium.com/@oleksiibukhantsov/interactive-graph-from-scratch-in-flutter-physics-animations-and-custompainter-dc43f233c198?source=rss-3830bbfa6692------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc43f233c198</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[physics-simulation]]></category>
            <dc:creator><![CDATA[Oleksii Bukhantsov]]></dc:creator>
            <pubDate>Mon, 04 Aug 2025 17:39:44 GMT</pubDate>
            <atom:updated>2025-08-18T14:53:59.967Z</atom:updated>
            <content:encoded><![CDATA[<h3>Interactive Knowledge Graph from scratch in Flutter: Physics, Animations, and CustomPainter</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTBhocNqktoQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FTBhocNqktoQ%3Ffeature%3Dshare&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTBhocNqktoQ%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f40dc3c838a48a3b7cbf55a6a7e445d/href">https://medium.com/media/9f40dc3c838a48a3b7cbf55a6a7e445d/href</a></iframe><p>I want to share my experience creating the interactive knowledge graph component. It’s built entirely in Flutter, without using any external graphics or physics libraries.</p><p>Let me first explain what this is all about.</p><p>Imagine you have a simplified knowledge base about your life and contacts. It includes only people, places, events, and groups of people. All these entities are connected by relationships.</p><p>For example, we know that</p><p>John Doe and his daughter Emily attended a DJ Nebula concert held at the &quot;Cosmic Pulse&quot; club.</p><p>From this, we can construct the following dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZArIBq77skd6QqUrvUEOw.png" /></figure><p>The task was to create a graphical visualization of such a dataset with basic editing capabilities, and ideally, with physics similar to those in the Graph View in Obsidian.</p><p>You can explore the demo project code via <a href="https://github.com/bambuh/social_graph_demo/">this link</a>.</p><h3>Physics</h3><p>In Obsidian’s Graph View, nodes behave as if they’re connected by springs. So I decided to implement a simple spring-based mechanic.</p><p>ChatGPT reminded me of Hooke’s Law, which describes the behavior of springs, and provided a <a href="https://gist.github.com/bambuh/51f11583091bc798936c7ebe6532c5ac">basic example</a>.</p><p>The idea is quite simple. The force acting on a body is directly proportional to the spring’s extension:</p><pre>force = stiffness * deltaLength</pre><p>Since we’re working in a 2D space, we also need to add the direction of the force as a normalized vector:</p><pre>forceVector = normalizedVector * stiffness * deltaLength</pre><p>You can treat force as acceleration, which lets you calculate the change in velocity and subsequently the new position:</p><pre>velocity = currentVelocity + force * deltaT<br>position = currentPosition + velocity * deltaT</pre><p>One final touch. We need to add damping so the system slows down over time and eventually stops.<br>This is done by multiplying the velocity by exp(-deltaT * damping):</p><pre>velocity = (currentVelocity + force * deltaT) * exp(-deltaT * damping)</pre><p>So I created models for bodies and springs:</p><pre>class Body {<br>  String id;<br>  Offset position;<br>  Offset velocity;<br>}<br><br>class Spring {<br>  String id;<br>  String body1Id;<br>  String body2Id;<br>  double targetLength;<br>  double stiffness;<br>  double damping;<br>}</pre><p>…and the PhysicsEngine with the following interface:</p><pre>abstract interface class PhysicsEngine extends ChangeNotifier {<br>  Map&lt;String, Body&gt; get bodies;<br>  Map&lt;String, Spring&gt; get springs;<br>  String? ignoreBodyId;  // ignore physics for this body when it&#39;s being dragged<br><br>  void addBody(Body body);<br>  void addSpring(Spring spring);<br>  void removeSpring(String id);<br>  void removeBody(String id);<br><br>  Offset getBodyPosition(String id);  // for rendering<br><br>  List&lt;({String id, double distance})&gt; getNearestObjects({  // to find the nearest node under the finger/cursor<br>    required Offset position,<br>    required double distance,<br>  });<br><br>  void updateBody(String id, {Offset? position, Offset? velocity});<br>}</pre><p>Internally, there’s a private method _updateWorld, which performs all the calculations described above on each tick (deltaT).</p><pre>void _updateWorld(Duration elapsed) {<br>  final deltaT = (elapsed.inMilliseconds - _latestTick) / 1000;<br>  _latestTick = elapsed.inMilliseconds;<br>  if (deltaT &lt;= 0) return;<br><br>  // iterate over all springs to update bodies velocities<br>  for (final spring in _springs.values) {<br>    final firstBody = _bodies[spring.body1Id];<br>    final secondBody = _bodies[spring.body2Id];<br>    if (firstBody == null || secondBody == null) continue;<br><br>    final displacement = secondBody.position - firstBody.position;<br><br>    // avoid division by zero<br>    final currentLength =<br>        displacement.distance == 0 ? minimumDistance : displacement.distance;<br><br>    final deltaLength = displacement.distance - spring.targetLength;<br><br>    final normalizedVector = displacement / currentLength;<br><br>    final forceVector =<br>        normalizedVector * spring.stiffness * deltaLength / 2.0;<br><br>    final deltaVelocity = forceVector * deltaT;<br><br>    Offset firstBodyVelocity = firstBody.velocity + deltaVelocity;<br>    Offset secondBodyVelocity = secondBody.velocity - deltaVelocity;<br><br>    // apply spring damping<br>    firstBodyVelocity *= exp(-deltaT * spring.damping);<br>    secondBodyVelocity *= exp(-deltaT * spring.damping);<br><br>    // update both bodies velocity<br>    updateBody(spring.body1Id, velocity: firstBodyVelocity);<br>    updateBody(spring.body2Id, velocity: secondBodyVelocity);<br>  }<br><br>  // iterate over all bodies to update their positions and apply global damping<br>  bool isChanged = false;<br>  for (final body in _bodies.values) {<br>    final velocity =<br>        body.velocity * exp(-deltaT * _damping); // apply global damping<br>    final position = body.position + velocity * deltaT;<br><br>    isChanged =<br>        isChanged ||<br>        position.dx.round() != body.position.dx.round() ||<br>        position.dy.round() != body.position.dy.round() ||<br>        velocity.distance &gt; minimumSignificantSpeed;<br><br>    updateBody(<br>      body.id,<br>      position: position,<br>      velocity: velocity,<br>    );<br>  }<br>  // stop ticker if no significant changes were made<br>  if (!isChanged) {<br>    _ticker.stop();<br>  }<br>  notifyListeners();<br>}</pre><h3>Node Placement</h3><p>Now I needed to figure out how to place the nodes from the dataset and apply physics to them.</p><p>Here’s the approach I came up with:</p><ul><li>All nodes are attached to their “positions” using springs with zero length. For this, I introduced a separate type of spring. These springs don’t connect two bodies, but instead, connect a body to a fixed point (anchor).</li><li>Nodes that are close to each other are connected with weak springs so that dragging one slightly pulls the others along.</li></ul><p>This already gave a great result (visible at the beginning of the video).<br>But I also wanted the nodes to group when zoomed out and to highlight their connections when selected.</p><p>To achieve this, I implemented a system for activating/deactivating springs by type. Each spring now has:</p><pre>final SpringType type;<br>final bool isActive;</pre><p>When creating springs, I assign them types such as the previously mentioned anchor and nearest, as well as the newer groupAnchor and selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Div56BPRPIVMmUiOum6mKA.gif" /></figure><p>The PhysicsEngine gained these methods:</p><pre>void removeSpringsByType(SpringType type);<br>void setSpringActive(String id, {required bool active});<br>void setSpringsActiveByType(SpringType type, {required bool active});<br>void setSpringsActiveByBodyId(String id, {required bool active});</pre><p>So, at a certain zoom level, I deactivate all anchor and nearest springs and activate groupAnchor springs that were previously inactive.<br>Likewise, when I select a node, I deactivate all other springs and add new selected ones to its related nodes.</p><p>It was fun to control everything this way! You toggle springs on and off, and physics takes care of the rest.<br>Even adding and removing nodes worked almost out of the box — just remove the old springs, calculate and add new ones, and the engine handles the magic.</p><h3>Viewport</h3><p>At first, I wanted to put everything into InteractiveViewer, but it didn’t work out. I needed gestures for tapping and dragging nodes, which conflicted with InteractiveViewer’s own GestureRecognizer.</p><p>So I built my own Viewport with a single GestureRecognizer that handles everything:</p><ul><li>tap on a node</li><li>drag a node</li><li>drag the whole viewport</li><li>zoom</li><li>rotate</li></ul><p>This introduced some new challenges:</p><ul><li>correctly converting coordinates between screen space and viewport space</li><li>smooth movement with inertia</li><li>rotation around the center point between two fingers (on mobile)</li><li>zoom toward the mouse cursor (on desktop)</li></ul><p>To achieve smooth motion, I reused the same PhysicsEngine for the viewport.<br>It contains a single body, whose position corresponds to the viewport’s offset.<br>Dragging the viewport updates this body position; on release, it keeps moving and gradually slows down due to damping.</p><p>When a node is selected, I add a strong spring of zero length between the viewport’s body and the node’s position. The viewport smoothly “flies” to center the node, and this spring is deleted after a second.</p><h3>Animations</h3><p><em>“Animations? Isn’t everything already animated?!”</em><br>Turns out I needed even more:</p><ul><li>animation for node size when adding/removing nodes</li><li>animation for the overlay appearing when a node is selected</li></ul><p>Since everything is rendered via CustomPainter on a canvas, I couldn’t use standard Animated widgets.<br>So I built a simple mechanism for animated parameters with this interface:</p><pre>abstract interface class AnimatedParams extends ChangeNotifier {<br>  double? get(String key);</pre><pre>  void addAnimation(<br>    String key, {<br>    required double from,<br>    required double to,<br>    required Duration duration,<br>    Curve curve = Curves.linear,<br>    void Function()? onComplete,<br>  });<br>}</pre><p>Now I can add the needed animated parameters and access their current value in the painter:</p><pre>final nodeRadius = defaultRadius * viewportState.scale *<br>  (animatedParams.get(&#39;${node.id}-scale&#39;) ?? 1.0);</pre><h3>All Together</h3><p>So we have:</p><ul><li>the main physics engine for nodes,</li><li>another one for the viewport,</li><li>and a third system for animated parameters.</li></ul><p>Each has its own Ticker. In the KnowledgeGraphView widget, there’s a master Ticker that checks if anything has changed and triggers a repaint.</p><p>The physics engine disables its ticker if all velocities are below a certain threshold.<br>Otherwise, it would keep recalculating and repainting constantly, even when nothing is moving, which would waste battery and heat up the device.</p><p>I’m deliberately not describing the CustomPainter drawing part here — it’s just lines and circles using high school geometry. There’s a lot of it, but it’s really not as scary as it sounds. 😉</p><h3>What Else</h3><p>It wasn’t mentioned, but relations in the dataset have directions, and we can switch them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*Y0WYQLFHU24YsZb5lTd_eQ.gif" /></figure><p>I also added a slight “space distortion” in the viewport to prevent empty gaps at the center when zoomed out and overlaps when zoomed in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*nJvI1dz00prQcHF3oIGs1w.gif" /></figure><h3>Summary</h3><p>In the end, I built my own Graph View that:</p><ul><li>runs on Flutter CustomPainters,</li><li>features spring-based physics, inertia, and smooth animations,</li><li>supports drag/zoom/rotate and node selection.</li></ul><p>I hope this experience will be useful to someone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc43f233c198" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Presentation events: a simple pattern for cleaner Flutter BLoC code]]></title>
            <link>https://medium.com/@oleksiibukhantsov/presentation-events-a-simple-pattern-for-cleaner-flutter-bloc-code-165502dd3bee?source=rss-3830bbfa6692------2</link>
            <guid isPermaLink="false">https://medium.com/p/165502dd3bee</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter-bloc]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Oleksii Bukhantsov]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 14:31:29 GMT</pubDate>
            <atom:updated>2025-08-01T14:31:29.441Z</atom:updated>
            <content:encoded><![CDATA[<p>Handle SnackBars, navigation, and other one‑time effects without cluttering your state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*0hE8DKkKEd8j8eGsgABcuQ.png" /></figure><h3>Intro</h3><p>If you use Flutter with the BLoC pattern, you’ve probably run into this problem:</p><blockquote><em>“I just want to show a temporary SnackBar or navigate to another page once, and the only way to notify the view about this is to emit a new state. But I don’t want to rebuild the whole view just for such one‑time events!”</em></blockquote><p>This article explains why one‑time UI events do not belong in your state and how to fix this with a clean and elegant approach.</p><p>For several years, our team had been using our internal custom extension for flutter_bloc. But while preparing this article, I discovered an existing package called <a href="https://pub.dev/packages/bloc_presentation"><strong>bloc_presentation</strong></a>, designed exactly for this purpose. So I’ll use that package to illustrate the approach.</p><h3>The problem: mixing effects and state</h3><p>In a typical BLoC:</p><ul><li>The <strong>view</strong> dispatches events to the bloc</li><li>The <strong>bloc</strong> updates the <strong>state</strong></li><li>The <strong>UI</strong> rebuilds when the state changes</li></ul><p>That works great for persistent UI state.<br> But sometimes you need <strong>transient effects</strong>, such as:</p><ul><li>Show a SnackBar once</li><li>Navigate to a different screen</li><li>Trigger an animation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*8jVJhyV_acz-Zi3ip8nirQ.gif" /></figure><p>To make things clear, let’s look at a very simple example app:</p><ul><li><em>The user needs to tap a button 50 times.</em></li><li><em>When the counter reaches 25 and 45, we want to show a temporary SnackBar with an encouraging message.</em></li><li><em>When the counter reaches 50, we want to navigate to a “Success” page.</em></li></ul><p>It’s a trivial scenario, but it demonstrates a common pain point:</p><blockquote><strong>How do we trigger these one‑time UI effects (SnackBar and navigation) from a bloc without polluting our state?</strong></blockquote><h3>The naive approach</h3><p>Most of us start by putting extra flags into the state.<br>For example, a simple int state in this Counter app can easily grow into something like this:</p><pre>class CounterState {<br>  final int counter; // &lt;- the only field that really represents the state of the view<br>  final String? snackbarMessage;<br>  final bool navigate;<br>}</pre><p>This leads to:</p><ul><li><strong>Polluted state</strong> — persistent state now contains temporary signals</li><li><strong>Unnecessary rebuilds</strong> — because showing a SnackBar triggers emit</li><li><strong>Boilerplate</strong> — you need to clear these fields right after showing them</li><li>buildWhen / listenWhen hacks everywhere</li></ul><p>There must be a better way.</p><h3>The idea: separate state and presentation events</h3><p>The key insight:</p><ul><li><strong>State</strong> describes what the UI <strong>is</strong> right now.</li><li><strong>Presentation events (effects)</strong> describe something the UI <strong>should do once</strong>.</li></ul><p>By emitting <strong>effects</strong> separately from the <strong>state</strong>, you keep your state clean and make effects easy to handle.</p><h4><a href="https://pub.dev/packages/bloc_presentation">bloc_presentation</a>: a small, focused solution</h4><p>bloc_presentation adds a <strong>second stream</strong> to your BLoC:</p><ul><li>emitPresentation() to send one‑time presentation events</li><li>BlocPresentationListener to listen for them in the UI</li></ul><p>Everything else stays exactly the same as flutter_bloc.</p><h3>Let’s apply this approach to the task we described</h3><p>You can find the <a href="https://gist.github.com/bambuh/fcbb2ccf3f4702512b9d2a191c0c7152">full code sample here</a>.</p><p>Define the presentation events</p><pre>// sealed class for one-time effects<br>sealed class CounterPresentationEvent {}<br><br>class ShowEncouragementSnackBar extends CounterPresentationEvent {<br>  final int remaining;<br>  ShowEncouragementSnackBar(this.remaining);<br>}<br><br>class NavigateToSuccessPage extends CounterPresentationEvent {}</pre><p>Create the cubit with BlocPresentationMixin</p><pre>import &#39;package:bloc_presentation/bloc_presentation.dart&#39;;<br><br>typedef CounterState = int;<br><br>class CounterCubit extends Cubit&lt;CounterState&gt;<br>    with BlocPresentationMixin&lt;CounterState, CounterPresentationEvent&gt; {<br>  CounterCubit() : super(0);<br><br>  void increment() {<br>    final newValue = state + 1;<br>    emit(newValue);<br><br>    if (newValue == 25 || newValue == 45) {<br>      final remaining = 50 - newValue;<br>      emitPresentation(ShowEncouragementSnackBar(remaining));<br>    } else if (newValue == 50) {<br>      emitPresentation(NavigateToSuccessPage());<br>    }<br>  }<br>}</pre><p>Note: apart from the BlocPresentationMixin and emitPresentation, it’s a normal Cubit.</p><p>Use BlocPresentationListener to handle effects separately from state:</p><pre>class CounterPage extends StatelessWidget {<br>  const CounterPage({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocPresentationListener&lt;CounterCubit, CounterPresentationEvent&gt;(<br>      listener: (context, event) {<br>        if (event is ShowEncouragementSnackBar) {<br>          ScaffoldMessenger.of(context).showSnackBar(<br>            SnackBar(<br>              content: Text(<br>                &#39;Keep it up! Only ${event.remaining} taps left.&#39;,<br>              ),<br>            ),<br>          );<br>        } else if (event is NavigateToSuccessPage) {<br>          Navigator.of(context).push(<br>            MaterialPageRoute(builder: (_) =&gt; const SuccessPage()),<br>          );<br>        }<br>      },<br>      child: BlocBuilder&lt;CounterCubit, CounterState&gt;(<br>        builder: (context, count) {<br>          return Scaffold(<br>            appBar: AppBar(title: const Text(&#39;Tap to 50&#39;)),<br>            body: Center(<br>              child: Column(<br>                mainAxisSize: MainAxisSize.min,<br>                children: [<br>                  const Text(<br>                    &#39;Tap the button until you reach 50!&#39;,<br>                    style: TextStyle(fontSize: 20),<br>                  ),<br>                  const SizedBox(height: 20),<br>                  Text(&#39;$count&#39;, style: const TextStyle(fontSize: 48)),<br>                  const SizedBox(height: 20),<br>                  ElevatedButton(<br>                    onPressed: () =&gt; context.read&lt;CounterCubit&gt;().increment(),<br>                    child: const Text(&#39;Tap me&#39;),<br>                  ),<br>                ],<br>              ),<br>            ),<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}</pre><p>The builder handles <strong>state</strong>, and the listener handles <strong>one-time presentation events</strong>.</p><p>Success page:</p><pre>class SuccessPage extends StatelessWidget {<br>  const SuccessPage({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return const Scaffold(<br>      body: Center(<br>        child: Text(<br>          &#39;Congratulations! You reached 50 taps!&#39;,<br>          style: TextStyle(fontSize: 20),<br>          textAlign: TextAlign.center,<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>Why is this better</h3><ul><li><strong>Clean state</strong> — no temporary flags</li><li><strong>Predictable</strong> — state and effects have different lifecycles</li><li><strong>Full compatibility</strong> — you can still use BlocBuilder, BlocListener, etc.</li><li><strong>Easy migration</strong> — just mix in BlocPresentationMixin and replace those temporary fields with emitPresentation()</li></ul><h3>Final thoughts</h3><p>This approach has made our BLoCs noticeably cleaner in several recent projects.</p><p>If you ever catch yourself adding fields like snackbarMessage or navigate: true to your state, or relying on buildWhen just to avoid rebuilding on one‑time actions, take it as a sign: it’s time to separate <strong>presentation effects</strong> from your <strong>state</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=165502dd3bee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>