<?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 Rostyslav Lesovyi on Medium]]></title>
        <description><![CDATA[Stories by Rostyslav Lesovyi on Medium]]></description>
        <link>https://medium.com/@rlesovyi?source=rss-e1e724ca80c4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*o8Ilsi3oexjt8PMl.jpg</url>
            <title>Stories by Rostyslav Lesovyi on Medium</title>
            <link>https://medium.com/@rlesovyi?source=rss-e1e724ca80c4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 10:12:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rlesovyi/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[Moving a 3D camera to perfectly fit entire scene]]></title>
            <link>https://rlesovyi.medium.com/moving-a-3d-camera-to-perfectly-fit-entire-scene-389d73d354d2?source=rss-e1e724ca80c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/389d73d354d2</guid>
            <category><![CDATA[viewport]]></category>
            <category><![CDATA[gamedev]]></category>
            <category><![CDATA[cameras]]></category>
            <dc:creator><![CDATA[Rostyslav Lesovyi]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 22:17:17 GMT</pubDate>
            <atom:updated>2024-02-10T22:17:17.928Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*TZxCktsb1tVfGsjEYbasQQ.png" /></figure><h3>Intro</h3><p>I had a simple task to perfectly fit entire 3D scene onto a viewport. There is only one limitation — I’m allowed to only change camera position, meaning that its rotation and fov are locked.</p><p>How hard can it be? Most probably for a seasoned game developer this is a trivial task but for a beginner it is quite an interesting challenge.</p><p>More over most solutions out there cover only simplified case with a single AABB or a sphere. But what to do if I have multiple objects or a cloud of vertices and single AABB is not precise enough?</p><h3>Quick note</h3><p>At first I probably need to describe what “perfect” means in this case. It means that the scene must touch top/bottom or left/right part of the viewport at any given time with any aspect ratio. I can allow myself to do some minimal shortcuts in the name of performance but algorithm should be able to make a real perfect fit in case precision is more important.</p><p>I will also be using GoDot with Rust binding for this arcticle but it can be easily translated to the language of your choice.</p><h3>Inspiration / Mentions</h3><p>First of all I need to be honest — this algorithm is not entirely my idea. It contains some optimizations like changing O(N²) to O(N) but the most interesting parts come from a single StackOverflow <a href="https://stackoverflow.com/a/66113254/855884">answer</a> I found that fits my requirements.</p><p>Well… I’m sure this question was answered many times in other places and I’m just bad at searching. Anyways.</p><h3>Lets start</h3><p>Before doing anything interesting lets create a simple scene:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8PyWIXP2mOKhLfOyy5ZFw.png" /></figure><p>And here is our beautiful render:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y-J0HpmK5PliGJVhSJmcLw.png" /></figure><h3>Algorithm</h3><p>General idea is pretty simple — we take camera frustum planes and find vertices on the edges of each plane. For our case we don’t care about near and far plane, we care only about left, top, right and bottom planes. Than we reposition our planes to the edge vertices and find their intersection point.</p><p>That’s it. Simple.</p><p>Now lets implement it. This is the result we want to achieve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cwVRTPRzgEiXucpB6gO4LQ.png" /></figure><p>Here red vertex is the leftmost vertex and green one is the rightmost vertex. Here is how it looks in the code:</p><pre>let frustum = camera.get_frustum();<br><br>// get frustum planes<br>let left_plane = frustum.get(2);<br>let right_plane = frustum.get(4);<br>let top_plane = frustum.get(3);<br>let bottom_plane = frustum.get(5);<br><br>// get edge vertices for each plane<br>let left_vertex = vertices.iter().max_by_key(|vertex| {<br>    OrderedFloat(left_plane.normal.dot(**vertex))<br>})?;<br>let right_vertex = vertices.iter().max_by_key(|vertex| {<br>    OrderedFloat(right_plane.normal.dot(**vertex))<br>})?;<br>let top_vertex = vertices.iter().max_by_key(|vertex| {<br>    OrderedFloat(top_plane.normal.dot(**vertex))<br>})?;<br>let bottom_vertex = vertices.iter().max_by_key(|vertex| {<br>    OrderedFloat(bottom_plane.normal.dot(**vertex))<br>})?;</pre><p>Now we have edge left, top, right and bottom vertices for our frustum planes. This is how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lJC7kqKZHZU-HUqTXvFhA.png" /></figure><p>Dots are the actual vertices selected (left = red, top = blue, right = green, bottom = magenta) and lines are the normal vectors for each plane.</p><p>Now we need to construct new frustum planes with the points we just discovered:</p><pre>let left_plane_new = Plane::from_point_normal(<br>    *left_vertex,<br>    left_plane.normal,<br>);<br>let right_plane_new = Plane::from_point_normal(<br>    *right_vertex,<br>    right_plane.normal,<br>);<br>let top_plane_new = Plane::from_point_normal(<br>    *top_vertex,<br>    top_plane.normal,<br>);<br>let bottom_plane_new = Plane::from_point_normal(<br>    *bottom_vertex,<br>    bottom_plane.normal,<br>);</pre><p>Next part is to find where these planes intersect. Unfortunately, we can’t have a single point with four planes… If it was that easy. Instead we’ll have two lines — one for left and right planes, second for top and bottom planes. Here is an example for horizontal planes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofZF6pVZdlviywJhMmYR7A.png" /></figure><p>In short this means that no vertex will ever be cropped horizontally if camera is placed anywhere on this line.</p><p>And this is intersection line for the vertical planes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99pw5zlnRfgQdCyHhq2qkw.png" /></figure><p>Same goes here — no vertex will ever be cropped vertically if camera is placed anywhere on this line.</p><p>Here is the code to find these lines:</p><pre>fn get_planes_intersection(p1: Plane, p2: Plane) -&gt; Option&lt;Ray&gt; {<br>    let p3normal = p2.normal.cross(p1.normal);<br>    let p3d = p3normal.length_squared();<br><br>    if p3normal.is_zero_approx() {<br>        return None;<br>    }<br><br>    Some(Ray {<br>        origin: ((p3normal.cross(p2.normal) * p1.d) + (p1.normal.cross(p3normal) * p2.d)) / p3d,<br>        direction: p3normal,<br>    })<br>}<br><br>let horizontal_intersection = get_planes_intersection(<br>    left_plane_new,<br>    right_plane_new,<br>)?;<br>let vertical_intersection = get_planes_intersection(<br>    top_plane_new,<br>    bottom_plane_new,<br>)?;</pre><p>Now we have two separate lines that most of the time will not overlap, what now? Well, we need to reduce this problem to finding two closest points between these lines:</p><pre>let a = line1.direction.dot(line1.direction);<br>let b = line1.direction.dot(line2.direction);<br>let e = line2.direction.dot(line2.direction);<br><br>let d = a * e - b * b;<br><br>let r = line1.origin - line2.origin;<br>let c = line1.direction.dot(r);<br>let f = line2.direction.dot(r);<br><br>let s = (b * f - c * e) / d;<br>let t = (a * f - c * b) / d;<br><br>let closest_point_line1 = line1.origin + line1.direction * s;<br>let closest_point_line2 = line2.origin + line2.direction * t;</pre><p>Only thing remaining is to choose which point to use for the camera position. Solution is simple — just choose the furthest point because it will cover more screen space:</p><pre>let camera_transform = camera.get_global_transform();<br>let camera_forward = camera_transform.basis * Vector3::FORWARD;<br><br>match (closest_point1 - closest_point2).dot(camera_forward) &lt; 0.0 {<br>    true =&gt; closest_point1,<br>    false =&gt; closest_point2,<br>}</pre><p>And voila, we can now perfectly fit entire scene on the viewport only by moving the camera:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*TXrupXJ1W5askEeSmi3s8g.gif" /></figure><h3>Full code</h3><pre>///<br>/// https://stackoverflow.com/a/66113254/855884<br>///<br>pub fn get_fit_to_viewport_position(camera: &amp;Camera3D, vertices: &amp;[Vector3]) -&gt; Option&lt;Vector3&gt; {<br>    let frustum = camera.get_frustum();<br><br>    // get frustum planes<br>    let left_plane = frustum.get(2);<br>    let right_plane = frustum.get(4);<br>    let top_plane = frustum.get(3);<br>    let bottom_plane = frustum.get(5);<br><br>    // get edge vertices for each plane<br>    let left_vertex = vertices.iter().max_by_key(|vertex| {<br>        OrderedFloat(left_plane.normal.dot(**vertex))<br>    })?;<br>    let right_vertex = vertices.iter().max_by_key(|vertex| {<br>        OrderedFloat(right_plane.normal.dot(**vertex))<br>    })?;<br>    let top_vertex = vertices.iter().max_by_key(|vertex| {<br>        OrderedFloat(top_plane.normal.dot(**vertex))<br>    })?;<br>    let bottom_vertex = vertices.iter().max_by_key(|vertex| {<br>        OrderedFloat(bottom_plane.normal.dot(**vertex))<br>    })?;<br><br>    // create new planes centered in the edge vertices<br>    let left_plane_new = Plane::from_point_normal(<br>        *left_vertex,<br>        left_plane.normal,<br>    );<br>    let right_plane_new = Plane::from_point_normal(<br>        *right_vertex,<br>        right_plane.normal,<br>    );<br>    let top_plane_new = Plane::from_point_normal(<br>        *top_vertex,<br>        top_plane.normal,<br>    );<br>    let bottom_plane_new = Plane::from_point_normal(<br>        *bottom_vertex,<br>        bottom_plane.normal,<br>    );<br>    <br>    // find lines of plane intersections<br>    let horizontal_intersection = get_planes_intersection(<br>        left_plane_new,<br>        right_plane_new,<br>    )?;<br>    let vertical_intersection = get_planes_intersection(<br>        top_plane_new,<br>        bottom_plane_new,<br>    )?;<br>    <br>    // find nearest point on the intersection lines<br>    let (closest_point1, closest_point2) = find_closest_points_on_two_lines(<br>        horizontal_intersection,<br>        vertical_intersection,<br>    );<br><br>    // find the closest point that is furthest from the scene<br>    let camera_transform = camera.get_global_transform();<br>    let camera_forward = camera_transform.basis * Vector3::FORWARD;<br><br>    Some(match (closest_point1 - closest_point2).dot(camera_forward) &lt; 0.0 {<br>        true =&gt; closest_point1,<br>        false =&gt; closest_point2,<br>    })<br>}<br><br>///<br>/// https://stackoverflow.com/a/32410473/2373034<br>/// Returns the intersection line of the 2 planes<br>///<br>fn get_planes_intersection(p1: Plane, p2: Plane) -&gt; Option&lt;Ray&gt; {<br>    let p3normal = p2.normal.cross(p1.normal);<br>    let p3d = p3normal.length_squared();<br><br>    if p3normal.is_zero_approx() {<br>        return None;<br>    }<br><br>    Some(Ray {<br>        origin: ((p3normal.cross(p2.normal) * p1.d) + (p1.normal.cross(p3normal) * p2.d)) / p3d,<br>        direction: p3normal,<br>    })<br>}<br><br>///<br>/// Returns the edge points of the closest line segment between 2 lines<br>///<br>fn find_closest_points_on_two_lines(line1: Ray, line2: Ray) -&gt; (Vector3, Vector3) {<br>    let a = line1.direction.dot(line1.direction);<br>    let b = line1.direction.dot(line2.direction);<br>    let e = line2.direction.dot(line2.direction);<br><br>    let d = a * e - b * b;<br><br>    let r = line1.origin - line2.origin;<br>    let c = line1.direction.dot(r);<br>    let f = line2.direction.dot(r);<br><br>    let s = (b * f - c * e) / d;<br>    let t = (a * f - c * b) / d;<br><br>    let closest_point_line1 = line1.origin + line1.direction * s;<br>    let closest_point_line2 = line2.origin + line2.direction * t;<br>    (closest_point_line1, closest_point_line2)<br>}</pre><p>Hope you liked it or even better — found it useful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=389d73d354d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing custom Widgets in Flutter (Part 3.b) — SimpleOverlay (no helpers)]]></title>
            <link>https://medium.com/geekculture/writing-custom-widgets-in-flutter-part-3-b-simpleoverlay-no-helpers-9ddf45cea983?source=rss-e1e724ca80c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ddf45cea983</guid>
            <category><![CDATA[renderobject]]></category>
            <category><![CDATA[custom-widget]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[widget]]></category>
            <category><![CDATA[slot]]></category>
            <dc:creator><![CDATA[Rostyslav Lesovyi]]></dc:creator>
            <pubDate>Mon, 14 Jun 2021 10:11:44 GMT</pubDate>
            <atom:updated>2021-06-14T15:51:06.357Z</atom:updated>
            <content:encoded><![CDATA[<h3>Writing custom Widgets in Flutter (Part 3.b) — SimpleOverlay (no helpers)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*J_f50bJMrdo4NmMPHylG5g.png" /></figure><h3>Intro</h3><p>As promised now I’ll show how to write SimpleOverlay Widget without any helpers. I’ll omit some boilerplate code which was already describer in previous articles.</p><h3>Quick Theory</h3><p>There are few more things we need to know when implementing Widgets that might contain multiple children.</p><p>The first thing we need to understand is the concept of the <strong>Slots</strong>. Slot is basically just a position of the child Widget inside our Widget. It has nothing to do with the x and y pixel coordinates, but rather logical position. For example in the case of a Toolbar it can represent navigation icon, logo, title or action (named Slots). But for Column it will be an index of each child.</p><p>Children Elements can also move from one Slot to a different one without recreation. For example when we specify <strong>GlobalKey</strong> for our child and then change its Slot during build method. Or when we call updateChid in our element and pass different Slot for the same Element.</p><p>One more thing is the order of calling children methods:</p><ul><li>Layout — order doesn’t matter unless one child size depends on the size of a different child</li><li>Paint — back-to-front order when children overlap each other, otherwise order doesn’t really matter</li><li>HitTest — front-to-back order when children overlap each other, otherwise order doesn’t really matter</li></ul><h3>Code</h3><p>The first difference is that our Widget will not extend <strong>MultiChildRenderObjectWidget</strong> anymore and instead will switch to the much simpler <strong>RenderObjectWidget</strong>:</p><pre><strong>class </strong>SimpleOverlay <strong>extends </strong>RenderObjectWidget {<br>  <strong>final </strong>Widget <strong>child</strong>;<br>  <strong>final </strong>Widget <strong>overlay</strong>;<br><br>  <strong>const </strong>SimpleOverlay({<br>    <strong>required this</strong>.<strong>child</strong>,<br>    <strong>required this</strong>.<strong>overlay</strong>,<br>  });<br><br>  @override<br>  RenderObjectElement createElement() {<br>    <strong>return </strong>SimpleOverlayElement(<strong>this</strong>);<br>  }<br><br>  @override<br>  RenderObject createRenderObject(BuildContext context) {<br>    <strong>return </strong>SimpleOverlayRenderObject();<br>  }<br>}</pre><p>Now we need to actually add children management logic to our Element:</p><pre><strong>class </strong>SimpleOverlayElement <strong>extends </strong>RenderObjectElement {<em><br>  </em>Element? <strong>_child</strong>;<br>  Element? <strong>_overlay</strong>;<br><br>  <em>// ...</em><br><br>  @override<br>  <strong>void </strong>mount(Element? parent, newSlot) {<br>    <strong>super</strong>.mount(parent, newSlot);<br><br>    <strong>_child </strong>= inflateWidget(<strong>widget</strong>.<strong>child</strong>, <strong>true</strong>);<br>    <strong>_overlay </strong>= inflateWidget(<strong>widget</strong>.<strong>overlay</strong>, <strong>false</strong>);<br>  }<br><br>  @override<br>  <strong>void </strong>update(SimpleOverlay newWidget) {<br>    <strong>super</strong>.update(newWidget);<br><br>    <strong>_child </strong>= updateChild(<strong>_child</strong>, newWidget.<strong>child</strong>, <strong>true</strong>);<br>    <strong>_overlay </strong>= updateChild(<strong>_overlay</strong>, newWidget.<strong>overlay</strong>, <strong>false</strong>);<br>  }<br><br>  @override<br>  <strong>void </strong>unmount() {<br>    <strong>super</strong>.unmount();<br>    <br>    <strong>_child </strong>= <strong>null</strong>;<br>    <strong>_overlay </strong>= <strong>null</strong>;<br>  }<br>}</pre><p>What is actually different here from the previous “no helper” example is the usage of the Slots. In case of the SimpleOverlay we have only two Slots — child and overlay. I chose to use Boolean as a Slot because we have only two possible values — <strong>true</strong> for the child and <strong>false</strong> for the overlay.</p><p>Again, just to be clear, Slots can be anything you want, but they should be consistent.</p><p>One more thing to add — is passing children RenderObjects lifecycle methods to our own:</p><pre><strong>class </strong>SimpleOverlayElement <strong>extends </strong>RenderObjectElement {<br>  <em>// ...</em><br><br>  @override<br>  <strong>void </strong>insertRenderObjectChild(RenderBox child, bool slot) {<br>    <strong>renderObject</strong>.insertRenderObjectChild(child, slot);<br>  }<br><br>  @override<br>  <strong>void </strong>moveRenderObjectChild(RenderBox child, bool oldSlot, bool newSlot) {<br>    <strong>renderObject</strong>.moveRenderObjectChild(child, oldSlot, newSlot);<br>  }<br><br>  @override<br>  <strong>void </strong>removeRenderObjectChild(RenderBox child, bool slot) {<br>    <strong>renderObject</strong>.removeRenderObjectChild(child, slot);<br>  }</pre><p>The only new thing here is the presence of the <strong>moveRenderObjectChild</strong> method. As I mentioned before, this method will be called when a child moves from the one Slot (<strong>oldSlot</strong>) to a new one (<strong>newSlot</strong>).</p><p>Thats all for our Element. Nothing really major, most of the code is the same. Now lets implement our RenderObject. First of all we need to handle insert, move and remove calls from our Element:</p><pre><strong>class </strong>SimpleOverlayRenderObject <strong>extends </strong>RenderBox {<br>  <em>//...</em></pre><pre><em>  </em>RenderBox? <strong>_child</strong>;<br>  RenderBox? <strong>_overlay</strong>;<br><br>  <strong>void </strong>insertRenderObjectChild(RenderBox child, bool slot) {<br>    <strong>if </strong>(slot) {<br>      <strong>_child </strong>= child;<br>    } <strong>else </strong>{<br>      <strong>_overlay </strong>= child;<br>    }<br>    adoptChild(child);<br>  }<br><br>  <strong>void </strong>moveRenderObjectChild(RenderBox child, bool oldSlot, bool newSlot) {<br>    <strong>if </strong>(oldSlot) {<br>      <strong>_child </strong>= <strong>null</strong>;<br>    } <strong>else </strong>{<br>      <strong>_overlay </strong>= <strong>null</strong>;<br>    }<br>    <strong>if </strong>(newSlot) {<br>      <strong>_child </strong>= child;<br>    } <strong>else </strong>{<br>      <strong>_overlay </strong>= child;<br>    }<br>  }<br><br>  <strong>void </strong>removeRenderObjectChild(RenderBox child, bool slot) {<br>    <strong>if </strong>(slot) {<br>      <strong>_child </strong>= <strong>null</strong>;<br>    } <strong>else </strong>{<br>      <strong>_overlay </strong>= <strong>null</strong>;<br>    }<br>    dropChild(child);<br>  }<em><br></em>}</pre><p>Slot, that we receive here, has the same value that we’ve passed to inflateWidget and updateChild in out Element before. Thanks to this Slot we know which RenderBox should go where. Also pay attention to the <strong>moveRenderObjectChild</strong> method — we don’t need to call <strong>adoptChild</strong> nor <strong>dropChild</strong> from it because child is actually reused and is already attached.</p><p>The very last thing that is new — is painting and hit testing:</p><pre><strong>class </strong>SimpleOverlayRenderObject <strong>extends </strong>RenderBox {<br>  <em>//...<br><br>  </em>@override<br>  <strong>void </strong>paint(PaintingContext context, Offset offset) {<br>    <strong>if </strong>(<strong>_child </strong>!= <strong>null</strong>) {<br>      context.paintChild(<strong>_child</strong>!, offset);<br>    }<br>    <strong>if </strong>(<strong>_overlay </strong>!= <strong>null</strong>) {<br>      context.paintChild(<strong>_overlay</strong>!, offset);<br>    }<br>  }<em><br><br>  </em>@override<br>  bool hitTestChildren(BoxHitTestResult result, {<strong>required </strong>Offset position}) {<br>    <strong>if </strong>(<strong>_overlay</strong>?.hitTest(result, position: position) == <strong>true</strong>) {<br>      <strong>return true</strong>;<br>    }<br>    <strong>if </strong>(<strong>_child</strong>?.hitTest(result, position: position) == <strong>true</strong>) {<br>      <strong>return true</strong>;<br>    }<br>    <strong>return false</strong>;<br>  }<em><br></em>}</pre><p>Please note the order in which we’re calling out children. We paint overlay last because we want it to be visible above our child but hit tests are using inverse order — overlay should take priority.</p><p>And here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*gf2KncvavhdjkJUQ.gif" /></figure><p>You can find implementation on my GitHub:<br><a href="https://github.com/MatrixDev/Flutter-CustomWidgets">https://github.com/MatrixDev/Flutter-CustomWidgets</a></p><p>Hope you liked it!</p><h3>Other articles:</h3><ul><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-1-ellipsizedtext-a0efdc1368a8">Part 1 — EllipsizedText</a></li><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-2-singlechildrenderobjectwidget-5637fecdf9bb">Part 2.a — ChildSize (with helpers)</a></li><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-2-b-childsize-no-helpers-61c578c9bbd2">Part 2.b — ChildSize (no helpers)</a></li><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-3a-simpleoverlay-with-helpers-6b3990db48b6">Part 3.a — SimpleOverlay (with helpers)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ddf45cea983" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/writing-custom-widgets-in-flutter-part-3-b-simpleoverlay-no-helpers-9ddf45cea983">Writing custom Widgets in Flutter (Part 3.b) — SimpleOverlay (no helpers)</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing custom Widgets in Flutter (Part 3.a) — SimpleOverlay (with helpers)]]></title>
            <link>https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-3a-simpleoverlay-with-helpers-6b3990db48b6?source=rss-e1e724ca80c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b3990db48b6</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[widget]]></category>
            <category><![CDATA[multichildrenderobject]]></category>
            <category><![CDATA[overlay]]></category>
            <category><![CDATA[custom-widget]]></category>
            <dc:creator><![CDATA[Rostyslav Lesovyi]]></dc:creator>
            <pubDate>Mon, 07 Jun 2021 10:12:35 GMT</pubDate>
            <atom:updated>2021-06-14T10:14:11.179Z</atom:updated>
            <content:encoded><![CDATA[<h3>Writing custom Widgets in Flutter (Part 3.a) — SimpleOverlay (with helpers)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*g8T0TrHaRtU-ox-sDcL8dg.png" /></figure><h3>Intro</h3><p>In previous articles we discussed how to create leaf Widget without children and Widget with a single child. Now it is time to create more complex Widget with multiple children.</p><p>Today I will describe how to create a SimpleOverlay Widget. The only thing it does is placing one Widget and overlaying it with a different Widget while keeping the size of the first Widget. It is such a simple concept but I’m using it quite often in my projects.</p><p>Hm… Can’t we use Stack for this? In the case when size of a child is known in advance — yes. But otherwise it doesn’t allow any dependencies between children.</p><p><strong>Update</strong>: you actually can use Stack for this with Positioned.filled(overlay) while also specifying Stack.fit to passthrough.</p><h3>Code</h3><p>First of all we need to create our own Widget:</p><pre><strong>class </strong>SimpleOverlay <strong>extends </strong>MultiChildRenderObjectWidget {<br>  SimpleOverlay({<br>    <strong>required </strong>Widget child,<br>    <strong>required </strong>Widget overlay,<br>  }) : <strong>super</strong>(children: [child, overlay]);<br><br>  @override<br>  RenderObject createRenderObject(BuildContext context) {<br>    <strong>return </strong>RenderSimpleOverlay();<br>  }<br>}</pre><p>This time instead of SingleChildRenderObjectWidget we extend MultiChildRenderObjectWidget because we have multiple children. This base class requires us to pass all children via constructor as a list. Order here does matter — painting is done from the first child to the last child while hit tests use reversed order.</p><p>Same as with SingleChildRenderObjectWidget, we don’t need to implement our own Element, everything is handled for us.</p><p>When using MultiChildRenderObjectWidget we need to declare one additional class — ContainerBoxParentData. Parent data allows us to store arbitrary data inside of each child directly (something similar to LayoutParams in Android). MultiChildRenderObjectWidget uses ParentData to store references to previous and next child resulting in a doubly linked list data structure for children storage:</p><pre><strong>class </strong>_SimpleOverlayChild <strong>extends </strong>ContainerBoxParentData&lt;RenderBox&gt;<br>    <strong>with </strong>ContainerParentDataMixin&lt;RenderBox&gt; {}</pre><p>Thats all, pretty simple. You can find mentioned about linked list references inside ContainerParentDataMixin:</p><pre><strong>mixin </strong>ContainerParentDataMixin&lt;ChildType <strong>extends </strong>RenderObject&gt; <strong>on </strong>ParentData {<br>  <em>/// The previous sibling in the parent&#39;s child list.<br>  </em>ChildType? <strong>previousSibling</strong>;<br>  <em>/// The next sibling in the parent&#39;s child list.<br>  </em>ChildType? <strong>nextSibling</strong>;<br>}</pre><p>Next thing is to create our RenderObject:</p><pre><strong>class </strong>RenderSimpleOverlay <strong>extends </strong>RenderBox<br>    <strong>with<br>        </strong>ContainerRenderObjectMixin&lt;RenderBox, _SimpleOverlayChild&gt;,<br>        RenderBoxContainerDefaultsMixin&lt;RenderBox, _SimpleOverlayChild&gt; {<br>  <em>// ...<br></em>}</pre><p>We must mix ContainerRenderObjectMixin in order to use our RenderObject with MultiChildRenderObjectWidget. This mixin contains logic for adding, attaching, moving, removing, detaching and iterating over children RenderObjects (in other words tons of mandatory boilerplate code). RenderBoxContainerDefaultsMixin by default doesn’t do anything at all but rather contains a few helpers to use when painting or hit testing.</p><p>Remember ParentData? Well, now we need to actually set it for each child:</p><pre><strong>class </strong>RenderSimpleOverlay {<br>  <em>// ...<br><br>  </em>@override<br>  <strong>void </strong>setupParentData(<strong>covariant </strong>RenderObject child) {<br>    child.<strong>parentData </strong>= _SimpleOverlayChild();<br>  }<em><br></em>}</pre><p>After that goes our usual layout logic:</p><pre><strong>class </strong>RenderSimpleOverlay {<br>  <em>// ...<br><br>  </em>@override<br>  <strong>void </strong>performLayout() {<br>    <strong>var </strong>childConstraints = <strong>constraints</strong>;<br><br>    <strong>final </strong>child = <strong>firstChild</strong>;<br>    <strong>if </strong>(child != <strong>null</strong>) {<br>      child.layout(<strong>constraints</strong>, parentUsesSize: <strong>true</strong>);<br>      childConstraints = BoxConstraints.tight(child.<strong>size</strong>);<br>    }<br><br>    <strong>final </strong>overlay = (child == <strong>null</strong>) ? <strong>null </strong>: childAfter(child);<br>    <strong>if </strong>(overlay != <strong>null</strong>) {<br>      overlay.layout(childConstraints, parentUsesSize: <strong>true</strong>);<br>    }<br><br>    <strong>size </strong>= child?.<strong>size </strong>?? overlay?.<strong>size </strong>?? <strong>constraints</strong>.<strong>smallest</strong>;<br>  }<em><br></em>}</pre><p>firstChild and childAfter are provided by ContainerRenderObjectMixin. If you recall, first child is our main child and second child is our overlay. We use childAfter instead of lastChild because firstChild and lastChild will return the same object when only one child is present (and this will result in a bug).</p><p>The last things we need to implement is painting and hit testing. And here comes RenderBoxContainerDefaultsMixin to the rescue:</p><pre><strong>class </strong>RenderSimpleOverlay {<br>  <em>// ...<br><br>  </em>@override<br>  <strong>void </strong>paint(PaintingContext context, Offset offset) {<br>    defaultPaint(context, offset);<br>  }<br><em><br>  </em>@override<br>  bool hitTestChildren(BoxHitTestResult result, {<strong>required </strong>Offset position}) {<br>    <strong>return </strong>defaultHitTestChildren(result, position: position);<br>  }<em><br></em>}</pre><p>And here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*HToy7tyC1gmc0D0VJHK9LQ.gif" /></figure><p>You can find implementation on my GitHub:<br><a href="https://github.com/MatrixDev/Flutter-CustomWidgets">https://github.com/MatrixDev/Flutter-CustomWidgets</a></p><p>Hope you liked it!</p><p>In the next article I’ll show how to achieve the same result without helpers manually.</p><h3>Other articles:</h3><ul><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-1-ellipsizedtext-a0efdc1368a8">Part 1 — EllipsizedText</a></li><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-2-singlechildrenderobjectwidget-5637fecdf9bb">Part 2.a — ChildSize (with helpers)</a></li><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-2-b-childsize-no-helpers-61c578c9bbd2">Part 2.b — ChildSize (no helpers)</a></li><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-3-b-simpleoverlay-no-helpers-9ddf45cea983">Part 3.b — SimpleOverlay (no helpers)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b3990db48b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing custom Widgets in Flutter (Part 2.b) — ChildSize (no helpers)]]></title>
            <link>https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-2-b-childsize-no-helpers-61c578c9bbd2?source=rss-e1e724ca80c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/61c578c9bbd2</guid>
            <category><![CDATA[custom-widget]]></category>
            <category><![CDATA[widget]]></category>
            <category><![CDATA[renderobject]]></category>
            <category><![CDATA[elements]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Rostyslav Lesovyi]]></dc:creator>
            <pubDate>Sun, 30 May 2021 21:05:54 GMT</pubDate>
            <atom:updated>2021-06-14T10:14:44.427Z</atom:updated>
            <content:encoded><![CDATA[<h3>Writing custom Widgets in Flutter (Part 2.b) — ChildSize (no helpers)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*y-Gv_EceFOeplCIRyKF2sA.png" /></figure><h3>Into</h3><p>In previous article we have created a custom Widget to notify us when its child size changes. To accomplish this task SingleChildRenderObjectWidget helper was used. It simplifies some parts of the code because we don’t need to write our own Element.</p><p>This time we will write everything from scratch. Writing Elements is not that hard but not without some tricky points. The main somewhat difficult thing to understand is how Element and RenderObject interacts with each other.</p><h3>Code</h3><p>To avoid repeating myself (and to keep this article reasonable size) I will describe only changes from the <a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-2-singlechildrenderobjectwidget-5637fecdf9bb">previous part</a>.</p><p>As before, first thing we need to do — create our widget. Here is what has changed:</p><pre><strong>class </strong>ChildSize <strong>extends </strong>RenderObjectWidget {<br>  <em>// ...<br>  </em><strong>final </strong>Widget? <strong>child</strong>;</pre><pre><strong>  const </strong>ChildSize({<br>    Key? key,<br>    <strong>this</strong>.<strong>child</strong>,<br>    <strong>this</strong>.<strong>onChildSizeChanged</strong>,<br>  }) : <strong>super</strong>(key: key);<br><br>  @override<br>  RenderObjectElement createElement() {<br>    <strong>return </strong>ChildSizeElement(<strong>this</strong>);<br>  }<br><br>  <em>// ...</em><br>}</pre><p>Our Widget now extends RenderObjectWidget instead of the SingleChildRenderObjectWidget. This base class doesn’t accept child Widget in its constructor so we need to store it by ourself.</p><p>Moreover, now we have additional method to implement — <strong>createElement</strong>. Here we need to return, you guessed it, our custom Element. This method will be called only once when the Widget is first inflated. After that Element will be reused until type of the Widget changes or we provide a different Key.</p><p>Now lets move to our Element:</p><pre><strong>class </strong>ChildSizeElement <strong>extends </strong>RenderObjectElement {<br>  ChildSizeElement(ChildSize widget) : <strong>super</strong>(widget);<br><br>  @override<br>  ChildSize <strong>get widget </strong>{<br>    <strong>return super</strong>.<strong>widget as </strong>ChildSize;<br>  }<br><br>  @override<br>  RenderChildSize <strong>get renderObject </strong>{<br>    <strong>return super</strong>.<strong>renderObject as </strong>RenderChildSize;<br>  }<br>}</pre><p>So far nothing special — we extended RenderObjectElement and override two getters. The latter ones are just to simplify the rest of the code (avoid casting widget and renderObject on each call).</p><p>Next we need to override three lifecycle callbacks:</p><pre><strong>class </strong>ChildSizeElement <strong>extends </strong>RenderObjectElement {<br>  <em>// ...<br>  </em>Element? <strong>_child</strong>;<br><br>  @override<br>  <strong>void </strong>mount(Element? parent, Object? newSlot) {<br>    <strong>super</strong>.mount(parent, newSlot);<br>    <strong>_child </strong>= updateChild(<strong>_child</strong>, <strong>widget</strong>.<strong>child</strong>, <strong>null</strong>);<br>  }<br><br>  @override<br>  <strong>void </strong>update(ChildSize newWidget) {<br>    <strong>super</strong>.update(newWidget);<br>    <strong>_child </strong>= updateChild(<strong>_child</strong>, newWidget.<strong>child</strong>, <strong>null</strong>);<br>  }<br><br>  @override<br>  <strong>void </strong>unmount() {<br>    <strong>super</strong>.unmount();<br>    <strong>_child </strong>= <strong>null</strong>;<br>  }<br>}</pre><ul><li><strong>mount</strong> — called when our Element is created and attached to its parent. Here we need to inflate all our children elements. In our case we have only one child.</li><li><strong>update</strong> — called when our Widget has changed. This might also change our child, so we need to update it as well.</li><li><strong>unmount</strong> — this is the final callback, at this point Element is destroyed. Now we can release the reference to our child.</li></ul><p>You might ask: “what is this <strong>updateChild</strong> method that we’re calling?”. This is the jack-of-all-trades method. It can do everything — create, update and delete Element, all in one call:</p><ul><li>First argument is a previous version of our child Element. If there is no Element available — null can be passed.</li><li>Second argument — new Widget for the child Element. Based on this Widget it will decide whether to reuse previous Element, or to delete it and create a new one.</li><li>Third argument is a slot. Slots are kind of interesting and can be anything — id, index, some other characteristic. The main point of slots is to identify child Element’s position. Because we have only one child — null can be passed.</li></ul><p>As a result of calling this method we will receive a new, previous (if reused) or null (if deleted) Element.</p><p>Okay, so far so good. But there are two more methods that must be implemented:</p><pre><strong>class </strong>ChildSizeElement <strong>extends </strong>RenderObjectElement {<br>  <em>// ...</em><br><br>  @override<br>  <strong>void </strong>visitChildren(ElementVisitor visitor) {<br>    <strong>final </strong>child = <strong>_child</strong>;<br>    <strong>if </strong>(child != <strong>null</strong>) {<br>      visitor(child);<br>    }<br>    <strong>super</strong>.visitChildren(visitor);<br>  }<br><br>  @override<br>  <strong>void </strong>forgetChild(Element child) {<br>    <strong>assert</strong>(child == <strong>_child</strong>);<br>    <strong>_child </strong>= <strong>null</strong>;<br>    <strong>super</strong>.forgetChild(child);<br>  }<br>}</pre><p>First one (<strong>visitChildren</strong>) is simply used by the Flutter to iterate over the children Elements. This is our responsibility because RenderObjectElement by itself doesn’t store any references to its children. Why? Simple, optimisations — we know better which data structure is best suited to store children and Flutter doesn’t limit us with indexes, unlike other frameworks.</p><p><strong>forgetChild</strong> as you might have guessed, is called when Element is removed and we also need to remove any references to the above Element. Usually this method is called during <strong>updateChild</strong> execution.</p><p>We are finally finished with children Elements management. But… it’s still not enough. Element will receive few more callbacks:</p><pre><strong>class </strong>ChildSizeElement <strong>extends </strong>RenderObjectElement {<br>  <em>// ...</em><br><br>  @override<br>  <strong>void </strong>insertRenderObjectChild(RenderBox child, <strong>covariant </strong>Object? slot) {<br>    <strong>renderObject</strong>.insertRenderObjectChild(child, slot);<br>  }<br><br>  @override<br>  <strong>void </strong>removeRenderObjectChild(RenderBox child, <strong>covariant </strong>Object? slot) {<br>    <strong>renderObject</strong>.removeRenderObjectChild(child, slot);<br>  }<br>}</pre><p>Here we need to inform our RenderObject when new children RenderObjects are added or removed. In reality there is one more callback which is called when a child RenderObject is moved from the old slot to the new one. But it doesn’t affect us because we have only a single slot.</p><p>PS: frankly, I don’t understand why Flutter team has added these callbacks to the Element instead of the RenderObject, but there might be some hidden reasons.</p><p>YEY. Now our Element is finally complete. Lets move to the RenderObject. Thankfully it needs less changes.</p><pre><strong>class </strong>RenderChildSize <strong>extends </strong>RenderBox {<br><em>  </em>RenderBox? <strong>_child</strong>;<em><br><br>  </em>@override<br>  <strong>void </strong>attach(<strong>covariant </strong>PipelineOwner owner) {<br>    <strong>super</strong>.attach(owner);<br>    <strong>_child</strong>?.attach(owner);<br>  }<br><br>  @override<br>  <strong>void </strong>detach() {<br>    <strong>super</strong>.detach();<br>    <strong>_child</strong>?.detach();<br>  }<br><br>  @override<br>  <strong>void </strong>visitChildren(RenderObjectVisitor visitor) {<br>    <strong>final </strong>child = <strong>_child</strong>;<br>    <strong>if </strong>(child != <strong>null</strong>) {<br>      visitor(child);<br>    }<br>    <strong>super</strong>.visitChildren(visitor);<br>  }<br><br>  @override<br>  <strong>void </strong>redepthChildren() {<br>    <strong>final </strong>child = <strong>_child</strong>;<br>    <strong>if </strong>(child != <strong>null</strong>) {<br>      redepthChild(child);<br>    }<br>    <strong>super</strong>.redepthChildren();<br>  }<em><br></em>}</pre><p>Those are self-explanatory. <strong>attach</strong>/<strong>detach</strong> are called when RenderObject is attached/detached from the parent. <strong>visitChildren</strong> is the same as in the Element but for the children RenderObjects.</p><p>The only new thing is <strong>redepthChildren</strong>. This is more of a helper for the debugging to know how deep RenderObjects tree goes.</p><p>And finally the last two methods which will actually add/remove our child:</p><pre><strong>class </strong>RenderChildSize <strong>extends </strong>RenderBox {<br>  <em>// ...</em><br><br>  <strong>void </strong>insertRenderObjectChild(RenderBox child, <strong>covariant </strong>Object? slot) {<br>    <strong>assert</strong>(<strong>_child </strong>== <strong>null</strong>);<br>    <strong>_child </strong>= child;<br>    adoptChild(child);<br>  }<br><br>  <strong>void </strong>removeRenderObjectChild(RenderBox child, <strong>covariant </strong>Object? slot) {<br>    <strong>assert</strong>(<strong>_child </strong>== child);<br>    <strong>_child </strong>= <strong>null</strong>;<br>    dropChild(child);<br>  }<em><br></em>}</pre><p>Nothing worth noting here except maybe <strong>adoptChild</strong> and <strong>removeChild</strong>. They mostly just set parent ParentData and set parent-child relations between RenderObjects.</p><p>Thats all, no more changes. As you can see SingleChildRenderObjectWidget helped us quite a lot and saved us from writing nearly 100 lines of boiler-plate code. I personally think that everyone needs to know how things work from the inside because sometimes helpers are just not enough.</p><p>And here is the result (the same as before, but now without the usage of the helpers):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*hQXH8UBjLrRWsDcN.gif" /></figure><p>You can find implementation on my GitHub:<br><a href="https://github.com/MatrixDev/Flutter-CustomWidgets">https://github.com/MatrixDev/Flutter-CustomWidgets</a></p><p>Hope you liked it!</p><h3>Other articles:</h3><ul><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-1-ellipsizedtext-a0efdc1368a8">Part 1 — EllipsizedText</a></li><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-2-singlechildrenderobjectwidget-5637fecdf9bb">Part 2.a — ChildSize (with helpers)</a></li><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-3a-simpleoverlay-with-helpers-6b3990db48b6">Part 3.a — SimpleOverlay (with helpers)</a></li><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-3-b-simpleoverlay-no-helpers-9ddf45cea983">Part 3.b — SimpleOverlay (no helpers)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61c578c9bbd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing custom Widgets in Flutter (Part 2.a) — ChildSize (with helpers)]]></title>
            <link>https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-2-singlechildrenderobjectwidget-5637fecdf9bb?source=rss-e1e724ca80c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5637fecdf9bb</guid>
            <category><![CDATA[renderobject]]></category>
            <category><![CDATA[size]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[widget]]></category>
            <category><![CDATA[custom-widget]]></category>
            <dc:creator><![CDATA[Rostyslav Lesovyi]]></dc:creator>
            <pubDate>Sat, 29 May 2021 08:28:20 GMT</pubDate>
            <atom:updated>2021-06-14T10:15:23.079Z</atom:updated>
            <content:encoded><![CDATA[<h3>Writing custom Widgets in Flutter (Part 2.a) — ChildSize (with helpers)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*QHJLLeEA_J-T2ABfi5uuXA.png" /></figure><h3>Intro</h3><p>The time has come for my second article. This time it will be a pretty simple Widget that notifies us when its child size changes. The task is pretty simple but the main point of it is to show you how to manage children in RenderObject.</p><p>When I just started with the Flutter it was one of the questions I had and even completing course on Udemy, sadly, I didn’t receive my answer. On the StackOverflow people advise to use GlobalKey on the Widget, finding its RenderObject and fetching size for it.</p><p>While there is nothing wrong with the above solution I still don’t like some things about it:</p><ul><li>it changes how Widget’s Element is destroyed</li><li>you need to add imperative code into declarative Widget structure</li><li>there is no ability to actually track size of the Widget and it needs to be pulled on demand</li></ul><p>In general what I want to achieve is following:</p><pre><strong>return </strong>ChildSize(<br>  child: buildChildWidget(),<br>  onChildSizeChanged: (size) =&gt; handleNewChildSize(size),<br>);</pre><h3>Brief theory</h3><p>When writing a custom Widget that contains children there are few important things we need to know:</p><ul><li>For each custom Widget we need to write its Element and (sometimes) RenderObject implementations</li><li>Element will inflate its children Widgets into a separate Elements and update/recreate them when needed</li><li>RenderObject has few important roles — children management, layout, paint and hit test (mouse pointers, touch events, etc.)</li></ul><h3>Code</h3><p>Lets start. First of all we need to declare an actual Widget:</p><pre><strong>class </strong>ChildSize <strong>extends </strong>SingleChildRenderObjectWidget {<br>  <strong>final void </strong>Function(Size)? <strong>onChildSizeChanged</strong>;<br><br>  <strong>const </strong>ChildSize({<br>    Key? key,<br>    Widget? child,<br>    <strong>this</strong>.<strong>onChildSizeChanged</strong>,<br>  }) : <strong>super</strong>(key: key, child: child);<br>}</pre><p>Nothing new here except SingleChildRenderObjectWidget. This is one of the helpers in the Flutter framework which allows us to write custom Widgets with no more than one child. This simplifies our code quite a lot because we don’t need to write custom Element at all.</p><p>The only thing we need to add to our Widget is the creation of the RenderObject and updating it when our Widget changes:</p><pre><strong>class </strong>ChildSize <strong>extends </strong>SingleChildRenderObjectWidget {<br>  <em>// ...</em><br><br>  @override<br>  RenderObject createRenderObject(BuildContext context) {<br>    <strong>return </strong>RenderChildSize()..<strong>_widget </strong>= <strong>this</strong>;<br>  }<br><br>  @override<br>  <strong>void </strong>updateRenderObject(BuildContext context, RenderChildSize renderObject) {<br>    renderObject..<strong>_widget </strong>= <strong>this</strong>;<br>  }<br>}</pre><p>Now we need to create our RenderObject:</p><pre><strong>class </strong>RenderChildSize <strong>extends </strong>RenderBox<br>    <strong>with </strong>RenderObjectWithChildMixin&lt;RenderBox&gt; {</pre><pre>  <strong>var _widget </strong>= <strong>const </strong>ChildSize();<br>}</pre><p>RenderObjectWithChildMixin is a special mixin that we must add when working with SingleChildRenderObjectWidget. This mixin will handle all the boring stuff (see next article). Almost each helper of this kind requires some mixin to be added. You can find these requirements in the documentation for each helper.</p><p>Next thing to do is to layout our child:</p><pre><strong>class </strong>RenderChildSize ... {<br>  <em>// ...<br>  </em><strong>var _lastSize </strong>= Size.<em>zero</em>;<br><br>  @override<br>  <strong>void </strong>performLayout() {<br>    <strong>final </strong>child = <strong>this</strong>.<strong>child</strong>;<br>    <strong>if </strong>(child != <strong>null</strong>) {<br>      child.layout(<strong>constraints</strong>, parentUsesSize: <strong>true</strong>);<br>      <strong>size </strong>= child.<strong>size</strong>;<br>    } <strong>else </strong>{<br>      <strong>size </strong>= <strong>constraints</strong>.<strong>smallest</strong>;<br>    }</pre><pre>    <strong>if </strong>(<strong>_lastSize </strong>!= <strong>size</strong>) {<br>      <strong>_lastSize </strong>= <strong>size</strong>;<br>      <strong>_widget</strong>.<strong>onChildSizeChanged</strong>?.call(<strong>_lastSize</strong>);<br>    }<br>  }<br>}</pre><p>During layout we must decide what size our RenderObject will have. To do that we need to layout our child. Our RenderObject’s size will be the same as the size of the child (we don’t have any paddings, margins, etc.).</p><p>Few important notes here:</p><ul><li>we must pass parentUsesSize = true to child’s layout function in order to get its size afterwards. Otherwise child.<strong>size</strong> will throw exception. Thanks to this flag Flutter can add additional optimisations.</li><li>there can be a case that even though we have a child Widget, there will be no child RenderObject for it. Not all Widgets have RenderObjects. In such case Flutter will try to provide us with nearest nested RenderObject if any exists.</li></ul><p>In this method we also check if size has changed and invoke the callback when it does.</p><p>The last things we need to do is to paint our child and to route hit test events:</p><pre><strong>class </strong>RenderChildSize <strong>...</strong> {<br>  <em>// ...<br></em><br>  @override<br>  <strong>void </strong>paint(PaintingContext context, Offset offset) {<br>    <strong>final </strong>child = <strong>this</strong>.<strong>child</strong>;<br>    <strong>if </strong>(child != <strong>null</strong>) {<br>      context.paintChild(child, offset);<br>    }<br>  }<br><br>  @override<br>  bool hitTestChildren(BoxHitTestResult result, {<strong>required </strong>Offset position}) {<br>    <strong>return child</strong>?.hitTest(result, position: position) == <strong>true</strong>;<br>  }<br>}</pre><p>And here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*H4YhjBTCNLfsaq_Ci9BySQ.gif" /></figure><p>You can find implementation on my GitHub:<br><a href="https://github.com/MatrixDev/Flutter-CustomWidgets">https://github.com/MatrixDev/Flutter-CustomWidgets</a></p><p>Hope you liked it!</p><p>In the next article I’ll show how to achieve the same result without helpers manually.</p><h3>Other articles:</h3><ul><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-1-ellipsizedtext-a0efdc1368a8">Part 1 — EllipsizedText</a></li><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-2-b-childsize-no-helpers-61c578c9bbd2">Part 2.b — ChildSize (no helpers)</a></li><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-3a-simpleoverlay-with-helpers-6b3990db48b6">Part 3.a— SimpleOverlay (with helpers)</a></li><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-3-b-simpleoverlay-no-helpers-9ddf45cea983">Part 3.b — SimpleOverlay (no helpers)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5637fecdf9bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing custom Widgets in Flutter (Part 1) — EllipsizedText]]></title>
            <link>https://itnext.io/writing-custom-widgets-in-flutter-part-1-ellipsizedtext-a0efdc1368a8?source=rss-e1e724ca80c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0efdc1368a8</guid>
            <category><![CDATA[leafrenderobjectwidget]]></category>
            <category><![CDATA[custom-widget]]></category>
            <category><![CDATA[ellipsis]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[widget]]></category>
            <dc:creator><![CDATA[Rostyslav Lesovyi]]></dc:creator>
            <pubDate>Thu, 27 May 2021 10:19:54 GMT</pubDate>
            <atom:updated>2021-06-15T07:12:13.757Z</atom:updated>
            <content:encoded><![CDATA[<h3>Writing custom Widgets in Flutter (Part 1) — EllipsizedText</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dFYac8EFMVpNLOIuLoyZDw.png" /></figure><h3>Intro</h3><p>Declarative UI in Flutter is pretty nice, easy to use and it is very enticing to use it as much as possible. But very often developers just go overboard with it — writing everything in a declarative style even when sometimes task can be done much more efficiently and easier to understand in a more imperative way.</p><p>What everyone should understand — there always must be a balance between declarative and imperative programming. Each has its own uses and each shines at some tasks brighter than other.</p><p>In this series of articles I’ll describe how to solve different problems by creating custom Widgets from scratch. Each one is a little more complicated than a previous one.</p><h3>Quick Theory</h3><p>There some basic things we need to know before looking at the code.</p><p>Widget — is just an immutable (preferably const) class that contains configuration properties for Elements and RenderObjects. It is also responsible for creating said Elements and RenderObjects. Important thing to understand — Widgets never contain state nor any business logic, only pass them.</p><p>Element — is an entity responsible for the actual UI tree. It has references to all children and (unlike Widget) to its parent. Elements are reused most of the time, unless key or Widget are changed. So if onlyWidget properties are changed, even though new Widget is allocated, Element will remain the same.</p><p>State — is nothing more than a user-defined class inside Element that also has some callbacks from itsElement exposed.</p><p>RenderObject — is responsible for actual size calculation, children placing, drawing, touch events handling and more. These objects are most closely resembling classic Views from Android or other frameworks.</p><p>Why do we have Elements and RenderObjects at the same time? Because of the efficiency. Each Widget has its respective Element, but only some have RenderObjects. Thanks to this a lot of layout, touch and other hierarchy traversal calls can be omitted.</p><h3>Code</h3><p>First example will be a pretty simple Widget that ellipsizes text when it doesn’t fit. Why do we need such a Widget when built-in Text has ellipsis support already you might ask? The answer is simple —as of this time it cuts only by words and not by characters (<a href="https://github.com/flutter/flutter/issues/18761">https://github.com/flutter/flutter/issues/18761</a>). So if you have a very long word at the end — most of the time you’ll see only the first letters of this word even when there is a plenty of space left to fill.</p><p>So lets start. Flutter has a lot of built-in base classes and mixins that will help with building fully custom Widgets. Here are few of them:</p><ul><li>LeafRenderObjectWidget — has no children</li><li>SingleChildRenderObjectWidget — has a single child</li><li>MultiChildRenderObjectWidget — has any number of children</li></ul><p>In our case we will use LeafRenderObjectWidget because we will only need to render text and there will be no children:</p><pre><strong>enum </strong>Ellipsis { <strong>start</strong>, <strong>middle</strong>, <strong>end </strong>}<br><br><strong>class </strong>EllipsizedText <strong>extends </strong>LeafRenderObjectWidget {<br>  <strong>final </strong>String <strong>text</strong>;<br>  <strong>final </strong>TextStyle? <strong>style</strong>;<br>  <strong>final </strong>Ellipsis <strong>ellipsis</strong>;<br><br>  <strong>const </strong>EllipsizedText(<br>    <strong>this</strong>.<strong>text</strong>, {<br>    Key? key,<br>    <strong>this</strong>.<strong>style</strong>,<br>    <strong>this</strong>.<strong>ellipsis </strong>= Ellipsis.<strong>end</strong>,<br>  }) : <strong>super</strong>(key: key);<br><br>  @override<br>  RenderObject createRenderObject(BuildContext context) {<br>    <strong>return </strong>RenderEllipsizedText()..<strong>widget </strong>= <strong>this</strong>;<br>  }<br><br>  @override<br>  <strong>void </strong>updateRenderObject(BuildContext context, RenderEllipsizedText renderObject) {<br>    renderObject.<strong>widget </strong>= <strong>this</strong>;<br>  }<br>}</pre><p>We have created our Widget. Only thing that is unusual — is a presence of two methods:</p><ul><li>createRenderObject — responsible for actually creating our RenderObject</li><li>updateRenderObject — will be called when Widget’s data changes but RenderObject remains the same. In this case we need to update data in RenderObject or otherwise it will render the old text.</li></ul><p>I also need to note that it is preferred to copy each value from the Widget to the RenderObject. But I will pass whole Widget, because they are immutable anyways (and I’m too lazy to write all that boilerplate code).</p><p>Now lets start with the actual RenderObject:</p><pre><strong>class </strong>RenderEllipsizedText <strong>extends </strong>RenderBox {<br>  <strong>var _widgetChanged </strong>= <strong>false</strong>;<br>  <strong>var _widget </strong>= <strong>const </strong>EllipsizedText(<strong>&#39;&#39;</strong>);<br><br>  <strong>set widget</strong>(EllipsizedText widget) {<br>    <strong>if </strong>(<strong>_widget</strong>.<strong>text </strong>== widget.<strong>text </strong>&amp;&amp;<br>        <strong>_widget</strong>.<strong>style </strong>== widget.<strong>style </strong>&amp;&amp;<br>        <strong>_widget</strong>.<strong>ellipsis </strong>== widget.<strong>ellipsis</strong>) {<br>      <strong>return</strong>;<br>    }<br>    <strong>_widgetChanged </strong>= <strong>true</strong>;<br>    <strong>_widget </strong>= widget;<br>    markNeedsLayout();<br>  }<br>}</pre><p>Here we defined all our variables and wrote a setter to actually update them. There is also a guard to check if values have actually changed — there is no need to recalculate ellipsis and redraw text if nothing has changed.</p><p>Now we need to layout our RenderObject.</p><pre><strong>class </strong>RenderEllipsizedText <strong>extends </strong>RenderBox {<br>  <em>// ...<br> </em> <strong>var _constraints </strong>= <strong>const </strong>BoxConstraints();<br><br>  @override<br>  <strong>void </strong>performLayout() {<br>    <strong>if </strong>(!<strong>_widgetChanged </strong>&amp;&amp; <strong>_constraints </strong>== <strong>constraints </strong>&amp;&amp; <strong>hasSize</strong>) {<br>      <strong>return</strong>;<br>    }<br><br>    <strong>_widgetChanged </strong>= <strong>false</strong>;<br>    <strong>_constraints </strong>= <strong>constraints</strong>;<br><br>    <strong>size </strong>=_ellipsize(<br>      minWidth: <strong>constraints</strong>.<strong>minWidth</strong>,<br>      maxWidth: <strong>constraints</strong>.<strong>maxWidth</strong>,<br>    );<br>  }<br>}</pre><p>Process of layout is pretty simple. All we need to do — calculate size of our RenderObject based on the constraints provided to us. Constraints only describe minimal and maximal size that we must comply. Also additional check is added if nothing has change and size was already calculated during previous layout pass.</p><p>Actual process of creating ellipsized text is pretty cumbersome and there are definitely better solution but I chose to use binary search to find best match.</p><pre><strong>class </strong>RenderEllipsizedText <strong>extends </strong>RenderBox {<br>  <em>// ...<br>  </em><strong>final _textPainter </strong>= TextPainter(textDirection: TextDirection.<strong>ltr</strong>);<br><br>  Size _ellipsize({<strong>required </strong>double minWidth, <strong>required </strong>double maxWidth}) {<br>    <strong>final </strong>text = <strong>_widget</strong>.<strong>text</strong>;<br><br>    <strong>if </strong>(_layoutText(length: text.<strong>length</strong>, minWidth: minWidth) &gt; maxWidth) {<br>      <strong>var </strong>left = 0;<br>      <strong>var </strong>right = text.<strong>length </strong>- 1;<br><br>      <strong>while </strong>(left &lt; right) {<br>        <strong>final </strong>index = (left + right) ~/ 2;<br>        <strong>if </strong>(_layoutText(length: index, minWidth: minWidth) &gt; maxWidth) {<br>          right = index;<br>        } <strong>else </strong>{<br>          left = index + 1;<br>        }<br>      }<br>      _layoutText(length: right - 1, minWidth: minWidth);<br>    }<br><br>    <strong>return constraints</strong>.constrain(Size(<strong>_textPainter</strong>.<strong>width</strong>, <strong>_textPainter</strong>.<strong>height</strong>));<br>  }<br>}</pre><p>I will not go through all of this logic (you can read trough it if you wish). But what is important is that TextPainter is used to calculate text size. If text size is longer than our constraints — I’ll try to make it shorter and shorter until it fits our constraints.</p><p>_layoutText is used to calculate our cropped text size:</p><pre>double _layoutText({<strong>required </strong>int length, <strong>required </strong>double minWidth}) {<br>  <strong>final </strong>text = <strong>_widget</strong>.<strong>text</strong>;<br>  <strong>final </strong>style = <strong>_widget</strong>.<strong>style</strong>;<br>  <strong>final </strong>ellipsis = <strong>_widget</strong>.<strong>ellipsis</strong>;<br><br>  String ellipsizedText = <strong>&#39;&#39;</strong>;<br><br>  <strong>switch </strong>(ellipsis) {<br>    <strong>case </strong>Ellipsis.<strong>start</strong>:<br>      <strong>if </strong>(length &gt; 0) {<br>        ellipsizedText = text.substring(text.<strong>length </strong>- length, text.<strong>length</strong>);<br>        <strong>if </strong>(length != text.<strong>length</strong>) {<br>          ellipsizedText = <strong>&#39;...&#39; </strong>+ ellipsizedText;<br>        }<br>      }<br>      <strong>break</strong>;<br>    <strong>case </strong>Ellipsis.<strong>middle</strong>:<br>      <strong>if </strong>(length &gt; 0) {<br>        ellipsizedText = text;<br>        <strong>if </strong>(length != text.<strong>length</strong>) {<br>          <strong>var </strong>start = text.substring(0, (length / 2).round());<br>          <strong>var </strong>end = text.substring(text.<strong>length </strong>- start.<strong>length</strong>, text.<strong>length</strong>);<br>          ellipsizedText = start + <strong>&#39;...&#39; </strong>+ end;<br>        }<br>      }<br>      <strong>break</strong>;<br>    <strong>case </strong>Ellipsis.<strong>end</strong>:<br>      <strong>if </strong>(length &gt; 0) {<br>        ellipsizedText = text.substring(0, length);<br>        <strong>if </strong>(length != text.<strong>length</strong>) {<br>          ellipsizedText = ellipsizedText + <strong>&#39;...&#39;</strong>;<br>        }<br>      }<br>      <strong>break</strong>;<br>  }<br><br>  <strong>_textPainter</strong>.<strong>text </strong>= TextSpan(text: ellipsizedText, style: style);<br>  <strong>_textPainter</strong>.layout(minWidth: minWidth, maxWidth: double.<em>infinity</em>);<br>  <strong>return _textPainter</strong>.<strong>width</strong>;<br>}</pre><p>Pretty much thats it. All we left to do — actually paint our text.</p><pre>@override<br><strong>void </strong>paint(PaintingContext context, Offset offset) {<br>  <strong>_textPainter</strong>.paint(context.<strong>canvas</strong>, offset);<br>}</pre><p>And here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*2Hiya57uQorSz1tMmRW0tA.gif" /></figure><p>You can find implementation on my GitHub:<br><a href="https://github.com/MatrixDev/Flutter-CustomWidgets">https://github.com/MatrixDev/Flutter-CustomWidgets</a></p><p>Hope you liked it!</p><h3>Other articles:</h3><ul><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-2-singlechildrenderobjectwidget-5637fecdf9bb">Part 2.a — ChildSize (with helpers)</a></li><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-2-b-childsize-no-helpers-61c578c9bbd2">Part 2.b — ChildSize (no helpers)</a></li><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-3a-simpleoverlay-with-helpers-6b3990db48b6">Part 3.a — SimpleOverlay (with helpers)</a></li><li><a href="https://rlesovyi.medium.com/writing-custom-widgets-in-flutter-part-3-b-simpleoverlay-no-helpers-9ddf45cea983">Part 3.b — SimpleOverlay (no helpers)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0efdc1368a8" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/writing-custom-widgets-in-flutter-part-1-ellipsizedtext-a0efdc1368a8">Writing custom Widgets in Flutter (Part 1) — EllipsizedText</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>