<?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 Mikhail &lt;mbixjkee&gt; Zotyev on Medium]]></title>
        <description><![CDATA[Stories by Mikhail &lt;mbixjkee&gt; Zotyev on Medium]]></description>
        <link>https://medium.com/@mbixjkee1392?source=rss-8bfe0fa05e74------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bDRoXloxi7SyEoUIFWjN9g@2x.jpeg</url>
            <title>Stories by Mikhail &amp;lt;mbixjkee&amp;gt; Zotyev on Medium</title>
            <link>https://medium.com/@mbixjkee1392?source=rss-8bfe0fa05e74------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 20:25:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mbixjkee1392/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[How does your sliver leave the screen?]]></title>
            <link>https://medium.com/@mbixjkee1392/how-does-your-sliver-leave-the-screen-c449a1557038?source=rss-8bfe0fa05e74------2</link>
            <guid isPermaLink="false">https://medium.com/p/c449a1557038</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[code-example]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[slivers]]></category>
            <dc:creator><![CDATA[Mikhail <mbixjkee> Zotyev]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 04:36:04 GMT</pubDate>
            <atom:updated>2023-07-05T04:36:04.451Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone! My name is <a href="https://github.com/MbIXjkee">Mikhail Zotyev</a>, I’m a software engineer, passionate about Dart and Flutter.</p><p>I explained a theoretical part of Sliver’s work in my <a href="https://medium.com/@mbixjkee1392/c6082f2c6b57">previous article</a>. Why do we need to know the theoretical part, if we don’t use it in practice? So in this article, I’ll share an example of how to build a specific effect with a custom sliver.</p><p>Do you remember Russ Hanneman from the Silicon Valley series and his remarkable attitude to car doors?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*MUDCKjfDZfsIVWtc" /></figure><p>Today we will create a sliver that Russ would like. No more boring leaving of the screen. Our sliver will rotate around the corner while moving away from the visible part of the screen. Let’s get this party started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*JR6PBvs64B2EP5--dmunlw.gif" /></figure><h3>Implementation</h3><p>First of all, our widget should contain something to show, and we will use special implementation on the rendering level. So we need to use <em>SingleChildRenderObjectWidget</em> to do this.</p><pre>class Spinner extends SingleChildRenderObjectWidget {<br>  const Spinner({<br>    Key? key,<br>    required Widget child,<br>  }) : super(key: key, child: child);<br><br>  @override<br>  RenderObject createRenderObject(BuildContext context) {<br>    return _SpinnerRenderSliver();<br>  }<br>}</pre><p>And the main part of this behavior will be implemented inside the <em>RenderObject</em>.</p><pre>class _SpinnerRenderSliver extends RenderSliver with<br>  RenderObjectWithChildMixin&lt;RenderBox&gt; {<br>    // ...<br>}</pre><p>So, how can we implement this behavior? First of all, we need to understand where the sliver is positioned. Depending on this position we need to decide, whether should it be rotated or not. If we need to rotate we also need to decide which angle it should be. And all these things can change in every new position, so we need to do these decisions in the layout method. But for the beginning, we need a few additional properties which will help us to store and apply our decisions.</p><pre>final _transformLayer = LayerHandle&lt;TransformLayer&gt;();<br>Matrix4? _paintTransform;</pre><p>Should content be rotated or not, <em>_paintTransform</em> shows. And when rotation is needed we need a <em>_transformLayer</em> for applying.</p><p>Let’s move to the <em>performLayout</em> method. As we’ve already discussed the rotation can change with position change. So to be independent of the previous calculation, we’ll reset <em>_paintTransform</em>.</p><pre>@override<br>  void performLayout() {<br>    _paintTransform = null;<br><br>   // …<br>}</pre><p>The next step is the calculation of the child size because it is crucial information for all other decisions. In order to do this, we need to convert <em>SliverConstraints</em> to <em>BoxConstraints</em> and provide it to the child.</p><pre>final constraints = this.constraints;<br>    child!.layout(constraints.asBoxConstraints(), parentUsesSize: true);<br>    final double childExtent;<br>    switch (constraints.axis) {<br>      case Axis.horizontal:<br>        childExtent = child!.size.width;<br>        break;<br>      case Axis.vertical:<br>        childExtent = child!.size.height;<br>        break;<br>}</pre><p>Now we have the size of the child, which means we know the maximum amount of space that our sliver can use. Based on this fact let’s calculate a few additional properties for SliverGeometry. We’ll use common methods of RenderSliver to do this.</p><p>The first of them is painted part of our sliver in current conditions.</p><pre>final paintedChildSize = calculatePaintOffset(<br>      constraints,<br>      from: 0.0,<br>      to: childExtent,<br>);</pre><p>The second is the part in the cache area in current constraints.</p><pre>final cacheExtent = calculateCacheOffset(<br>      constraints,<br>      from: 0.0,<br>      to: childExtent,<br>);</pre><p>So now we are ready to describe the geometry.</p><pre>geometry = SliverGeometry(<br>      scrollExtent: childExtent,<br>      paintExtent: paintedChildSize,<br>      cacheExtent: cacheExtent,<br>      maxPaintExtent: childExtent,<br>      hitTestExtent: paintedChildSize,<br>      hasVisualOverflow: childExtent &gt; constraints.remainingPaintExtent ||<br>          constraints.scrollOffset &gt; 0.0,<br>);</pre><p>And additionally, we need to adjust the child using this geometry by setting the paintOffset according to the axisDirection and growthDirection.</p><pre>void _setChildParentData(<br>    RenderObject child,<br>    SliverConstraints constraints,<br>    SliverGeometry geometry,<br>  ) {<br>    final childParentData = child.parentData! as SliverPhysicalParentData;<br>    var dx = 0.0;<br>    var dy = 0.0;<br>    switch (applyGrowthDirectionToAxisDirection(<br>      constraints.axisDirection,<br>      constraints.growthDirection,<br>    )) {<br>      case AxisDirection.up:<br>        dy = -(geometry.scrollExtent -<br>            (geometry.paintExtent + constraints.scrollOffset));<br>        break;<br>      case AxisDirection.right:<br>        dx = -constraints.scrollOffset;<br>        break;<br>      case AxisDirection.down:<br>        dy = -constraints.scrollOffset;<br>        break;<br>      case AxisDirection.left:<br>        dx = -(geometry.scrollExtent -<br>            (geometry.paintExtent + constraints.scrollOffset));<br>        break;<br>    }<br><br>    childParentData.paintOffset = Offset(dx, dy);<br>  }</pre><p>Okay, we’ve done base things regarding the size of the sliver and now we can care about rotation. We need to rotate our sliver only if part of it has already left the viewport. It is easy to detect with the scrollOffset value.</p><pre>final scrollOffset = constraints.scrollOffset;<br><br>if (scrollOffset &gt; 0 &amp;&amp; paintedChildSize &gt; 0) {<br>    // …<br>}</pre><p>Let’s calculate the angle. The more part is outside the screen, the more angle we will use. We know the maximum size and the painted size, so it will be easy for us</p><pre>final angle = _kQuarterTurnsInRadians * (1 - paintedChildSize / childExtent);</pre><p>But we cannot just apply the turn, because we need to turn around the left bottom corner, but the default point of turn is center. We need to make a small trick</p><pre>final translation = FractionalOffset.bottomLeft.alongSize(<br>        Size(<br>          child!.size.width,<br>          paintedChildSize,<br>        ),<br>);<br><br>_paintTransform = Matrix4.identity()<br>        ..translate(0.0, translation.dy)<br>        ..rotateZ(-angle)<br>        ..translate(0.0, -translation.dy);</pre><p>Let’s put everything together and look at the whole method</p><pre>@override<br>void performLayout() {<br>  _paintTransform = null;<br><br>  final constraints = this.constraints;<br>  child!.layout(constraints.asBoxConstraints(), parentUsesSize: true);<br>  final double childExtent;<br>  switch (constraints.axis) {<br>    case Axis.horizontal:<br>      childExtent = child!.size.width;<br>      break;<br>    case Axis.vertical:<br>      childExtent = child!.size.height;<br>      break;<br>  }<br><br>  final paintedChildSize = calculatePaintOffset(<br>    constraints,<br>    from: 0.0,<br>    to: childExtent,<br>  );<br>  final cacheExtent = calculateCacheOffset(<br>    constraints,<br>    from: 0.0,<br>    to: childExtent,<br>  );<br><br>  final scrollOffset = constraints.scrollOffset;<br><br>  if (scrollOffset &gt; 0 &amp;&amp; paintedChildSize &gt; 0) {<br>    final translation = FractionalOffset.bottomLeft.alongSize(<br>      Size(<br>        child!.size.width,<br>        paintedChildSize,<br>      ),<br>    );<br><br>    final angle =<br>      _kQuarterTurnsInRadians * (1 - paintedChildSize / childExtent);<br><br>    _paintTransform = Matrix4.identity()<br>      ..translate(0.0, translation.dy)<br>      ..rotateZ(-angle)<br>      ..translate(0.0, -translation.dy);<br>  }<br><br>  assert(paintedChildSize.isFinite);<br>  assert(paintedChildSize &gt;= 0.0);<br>  geometry = SliverGeometry(<br>    scrollExtent: childExtent,<br>    paintExtent: paintedChildSize,<br>    cacheExtent: cacheExtent,<br>    maxPaintExtent: childExtent,<br>    hitTestExtent: paintedChildSize,<br>    hasVisualOverflow: childExtent &gt; constraints.remainingPaintExtent ||<br>      constraints.scrollOffset &gt; 0.0,<br>  );<br><br>  _setChildParentData(child!, constraints, geometry!);<br>}</pre><p>The layout is ready, but it is not enough only calculate it, we need paint. And for the painting, we will use that special layer, that we created in the beginning</p><pre>@override<br>void paint(PaintingContext context, Offset offset) {<br>  if (child != null &amp;&amp; geometry!.visible) {<br>    _transformLayer.layer = context.pushTransform(<br>      needsCompositing,<br>      offset,<br>      _paintTransform ?? Matrix4.identity(),<br>      _paintChild,<br>      oldLayer: _transformLayer.layer,<br>    );<br>  } else {<br>    _transformLayer.layer = null;<br>  }<br>}</pre><p>The <em>_paintChild</em> method just paints the child</p><pre>void _paintChild(PaintingContext context, Offset offset) {<br>  final childParentData = child!.parentData! as SliverPhysicalParentData;<br>  context.paintChild(child!, offset + childParentData.paintOffset);<br>}</pre><p>And the final touch, we need to handle cases when beyond our transform we have another one:</p><pre>@override<br>void applyPaintTransform(covariant RenderObject child, Matrix4 transform) {<br>  if (_paintTransform != null) {<br>    transform.multiply(_paintTransform!);<br>  }<br>  final childParentData = child.parentData! as SliverPhysicalParentData;<br><br>  childParentData.applyPaintTransform(transform);<br>}</pre><p>So that’s it. Now we have a widget with interesting behavior that we wanted to implement.</p><h3>Conclusion</h3><p>Hope this example will help you don’t be afraid of internal work with the Sliver protocol and create a lot of perfect scroll effects.</p><p>I’ve formed this implementation in a small package that is available in pub — sliver_spinner.</p><p><a href="https://pub.dev/packages/sliver_spinner">sliver_spinner | Flutter Package</a></p><p>And the source code you can find in GitHub.</p><p><a href="https://github.com/MbIXjkee/sliver_spinner">GitHub - MbIXjkee/sliver_spinner</a></p><p>Stay on the 🎯 Dart side of the Force ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c449a1557038" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slivers or how scrolling works]]></title>
            <link>https://medium.com/@mbixjkee1392/slivers-or-how-scrolling-works-c6082f2c6b57?source=rss-8bfe0fa05e74------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6082f2c6b57</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[slivers]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Mikhail <mbixjkee> Zotyev]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 04:33:41 GMT</pubDate>
            <atom:updated>2023-07-05T04:33:41.789Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone! My name is <a href="https://github.com/MbIXjkee">Mikhail Zotyev</a>, I’m a software engineer, passionate about Dart and Flutter.</p><p>In this article, I want to talk about Slivers. If you feel this picture with the word Sliver, you’ve definitely already worked with them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/0*lLXbpVVH8Ow3Ypq3.jpg" /></figure><p>Slivers are usually pretty much demonized, especially by beginners in the topic, because of the underhood complexity. When we start to figure out how Slivers work and see all kinds of responsibilities and entities, we understand that the TV series Dark is pretty straightforward and not at all twisted compared to them. But in order to make good use of the Slivers we need to understand their inner workings. That is a bit unusual requirement for a Flutter person because we used to have everything easy and high-level when working with Flutter. Therefore, quite often people decide that it is not worth spending time learning Slivers and prefer to do hacks instead of them.</p><p>Today we gonna fix it, explore all these internal secrets of Slivers, and will become able to implement any magic scrolling behavior we ever can imagine. Let’s go on this journey.</p><h3>What is a Sliver and why do we need them?</h3><p>This question will be our entry point. To answer let’s recall how Flutter builds layout. I’m sure you are familiar with this, but let’s recall this information anyway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*4lYatPwV7iYXpxDBRWP4JA.png" /></figure><p>Render Objects are responsible for this. Three rules make it possible:</p><ul><li>Constraints go down by the tree from the parents to the children.</li><li>Sizes go up by the tree from the children to the parents.</li><li>Parents set the position of the children.</li></ul><p>In general, when we say “constraints” we mean BoxConstraints. BoxConstraint has only 4 properties — minimal and maximum width, minimal and maximum height.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*hx-AEha-ZoAtrJ7KGOsz5g.png" /></figure><p>We give these constraints to the layout method and want to get back a size. But it works for general cases, so let’s look closer at scrolling.</p><p>For example, let’s take a rather common Android AppBar behavior when it changes its state based on scroll progress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*dlC7JqXyLjt9pK5nCvieHg.gif" /></figure><p>When we scroll AppBar becomes less in size before it disappears completely. We continue to scroll further for a long time and when we change the scrolling direction, AppBar appears anyway irrespectively of how much content we’ve scrolled. And it is one of the common UX for scrolling. But this behavior is hard or even impossible to implement with BoxConstraints, because it has too few properties for defining the object’s size and position, so we need a more flexible approach, let’s call it a Sliver Protocol.</p><p>But you shouldn’t think that Sliver Protocol is something fundamentally different. The rules are the same, but we get flexibility by using more detailed objects for constraints and sizes, that is SliverConstraints And SliverGeometry.</p><p>So, the first simple conclusion:</p><blockquote>Slivers are widgets with a more flexible approach to layout.</blockquote><h3>How to implement scrolling?</h3><p>Before we start to figure out the internal implementation of SliverConstraints and SliverGeometry, I would like to offer you a small game. Let’s imagine that Flutter doesn’t exist and we are working on the creation of our own Flutter, where we need to implement a scrolling system. What should we do? Think to yourselves, and then check on my version below.</p><p>From my point of view, we need 3 responsibilities here.</p><ul><li>The interaction layer detects user gestures.</li><li>The container stores all objects which we want to scroll.</li><li>The content that should be scrolled.</li></ul><p>Let’s return to Flutter and check how scrolling works there. Not surprisingly, our views on this question coincide. Let’s check the concrete entities responsible for each part one by one.</p><h3>Scrollable</h3><p>The first responsibility, as we mentioned, is working with user gestures. For that, scrollable is responsible.</p><p>What is scrollable? The documentation tells us:</p><blockquote>Scrollable is a widget that scrolls.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FHtBKcjpHfD7s4%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fhappy-time-smiling-HtBKcjpHfD7s4&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZHkzYnR4ZXhmN2FkM3ZjaXhoeTZmY2RkZ3RtNGwwZHliMTJudmVydSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FHtBKcjpHfD7s4%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="317" frameborder="0" scrolling="no"><a href="https://medium.com/media/96bceac2572232a1d941c04d059f8a67/href">https://medium.com/media/96bceac2572232a1d941c04d059f8a67/href</a></iframe><p>But without jokes, it is the only thing that we need to know about Scrollable. It is the interaction layer, that includes gesture recognition but doesn’t have a clue about the content, what is shown, etc.</p><h3>Viewport</h3><p>The next responsibility is a container for scrolled content. In Flutter it is a Viewport class, the subclass of MultiChildRenderObjectWidget.</p><p>Viewport is the visual workhorse of the scrolling machinery. Its inner size is more than its out size, like a black hole in the space of Flutter. Viewport is used in all scrollable widgets, whether it’s a ListView, PageView, or CustomScrollView, you’ll find a Viewport combined with a Scrollable in all of them.</p><p>Since Viewport is a container for scrolling, it should have two directions:</p><p><em>axisDirection</em> — the direction in which offset is increased. Based on this we decide which edge is leading and trailing for the viewport.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*vItqVVK3bPTJtBrfmx576A.png" /></figure><p><em>crossAxisDirection</em> — The direction in which a child should be laid out perpendicular to the axisDirection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*6_mZT6G8x6tKILVPiD9poQ.png" /></figure><p>If we have two axes we have a point of their crossing. This point is called an anchor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*hkNzMm1MAPbmvMhfOKw1HQ.png" /></figure><p>Where is it? Regarding the left or right side — it depends on crossAxisDirection. And the position by the main axis can be set. The whole viewport size by the main axis is a segment from 0 to 1 increasing by the axisDirection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*a4n1T0JNjrz2rqJgG5tunw.png" /></figure><p>The anchor value is zero by default. And it means that in the very common case when the axisDirection is down and the crossAxisDirection is right, the anchor is the top left corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*IGZbrwrrVo5Fmu35tjT21w.png" /></figure><p>But we can set anchor 0.5 for example and we move the anchor to the middle of the main axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*0J0mdWburLH0YdQ8gHW2bQ.png" /></figure><p>But why do we need it? Because the anchor is much more than just a crossing point. This is a point of alignment of the <em>center sliver</em>, which is a rather important one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Wv_TIQlgh4a7PG02NzlIww.png" /></figure><p>This is the sliver, relative to which other slivers grow. All slivers after the center one, grow in the forward direction, and those before the center one grow in the reverse direction. The default center sliver is the very first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*zTKSn0yyIXY2Q8QGSd119A.png" /></figure><p>But we can change it by setting up a key for the center sliver.</p><p>How can we use it? When the offset is 0, the center sliver is positioned right at the anchor. And all the following calculations will be performed in relation to this sliver.</p><p>One more crucial thing which we must know about viewport is the cache. It is necessary to make the scrolling smooth. Thanks to the cache area the content can be prepared before it should appear. But it is not enough to only care about one direction because the content can appear from the opposite as well. So we must not destroy the content as soon as it leaves the visible part. This means we need two cache areas — one before the trailing edge and one after the leading edge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*4Fmaf-CaPqEZuz0Vw_L48w.png" /></figure><p>The default size of them is 250. So the full size handled by the viewport is the cache size before the trailing edge + the main axis viewport size + the cache size after the leading edge.</p><h3>Let’s put it together</h3><p>We have looked at Viewport and Scrollable separately from each other, now let’s put it together.</p><p>We’ll describe a common situation when the main axis is vertical and axisDirection is down. In the same manner, you can scale this to all other variants easily. For clarity, all elements have a number from 0 to 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*vx5D3qKIIGGtrktDqLbWXw.png" /></figure><p>There are two different variants on the left and right as you can see. And their difference is in the growthDirection property. If every next element (with the bigger number) appears in the same direction as axisDirection, the growthDirection is forward, otherwise reverse.</p><p>We remember that Scrollable works with user interaction. This interaction is described by the userScrollDirection property. It can have a few values. When the user doesn’t touch a screen it is ScrollDirection.idle. When the user touches the screen but doesn’t move a finger it is also is ScrollDirection.idle. When a user starts to make a scroll the userScrollDirection can be ScrollDirection.forward or ScrollDirection.reverse. It depends on the direction of the movement the user makes. If the movement makes the next element appear, this is ScrollDirection.forward. If it’s the previous one, this is ScrollDirection.reverse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*LPTajX786WcKk4wVUXX8Iw.gif" /></figure><h3>Content</h3><p>And we have come to the last topic — the content which we scroll that is slivers. As we already know, they are common widgets but with a little difference — more detailed layout building and rendering.</p><p>To make following the topic easier I have prepared a little <a href="https://mbixjkee.github.io/constraints_info/">application</a> for you. It will help you to comfortably discover this part with me and maybe have experiments in the future.</p><h4>SliverConstraints</h4><p>We will start with the SliverConstraints. It has a lot of properties that we have already become familiar with while figuring out the viewport.</p><p><strong><em>axis</em></strong></p><p>The axis along which the scrollOffset and remainingPaintExtent are measured.</p><p><strong><em>axisDirection</em></strong></p><p>The direction in which the scrollOffset and remainingPaintExtent increase.</p><p><strong><em>growthDirection</em></strong></p><p>The direction in which the contents of slivers are ordered, relative to the axisDirection.</p><p><strong><em>crossAxisDirection</em></strong></p><p>The direction in which children should be placed on the cross-axis.</p><p><strong><em>isNormalized</em></strong></p><p>Whether the constraint is expressed in a consistent manner. The consistent means the axisDirection is an AxisDirection.down or AxisDirection.right.</p><p><strong><em>normalizedGrowthDirection</em></strong></p><p>Returns consistent constraints.</p><p><strong><em>isTight</em></strong></p><p>Whether constraints are tight. The tight constraints are the constraints when exactly one size is possible given these constraints.</p><p><strong><em>viewportMainAxisExtent</em></strong></p><p>The number of pixels the viewport can display on the main axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*0WdGuny4DyLW-aBlTK7-UA.png" /></figure><p><strong><em>crossAxisExtent</em></strong></p><p>The number of pixels in the cross-axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*_Q0mxd88At8IpmkAhrHjtQ.png" /></figure><p><strong><em>userScrollDirection</em></strong></p><p>The direction in which the user is attempting to scroll.</p><p><strong><em>scrollOffset</em></strong></p><p>This is an important property of sliver protocol. It describes the offset of the earliest visible part of the sliver relative visible part of the viewport.</p><p>Before crossing the edge of the viewport the value is 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*SMs0Q15LWJxYKIZtRTZThw.png" /></figure><p>The default example can be a little confusing because the viewport edge is in the same place as the anchor. It is important to note that point of calculation is the edge of the viewport, not the anchor. If we move the anchor to the middle, crossing it will not make the value different from 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*lC6IcKpbi5RMNNeE7wcwog.png" /></figure><p>As soon the sliver crosses the edge the scrollOffset starts growing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*G0BX4uIbJ558JRQ1OYyDLg.png" /></figure><p>And of course, if the axis direction changes, the leading edge also changes, so the scrollOffset calculates relative to another edge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Sf3jXwNIafUzg_8PRfqrVw.png" /></figure><p><strong><em>precedingScrollExtent</em></strong></p><p>The scroll distance that has been consumed by all RenderSlivers that came before this RenderSliver.</p><p>It looks pretty simple but has a tricky edge case.</p><p>Often slivers create their content lazily (for example SliverList). In this case, when the whole internal content of this sliver is much more than the viewport size, additional content will be created only if needed, when layout occurs. This means that this Sliver doesn’t have enough information to estimate its total extent. So precedingScrollExtent will be infinite for all slivers after this sliver. But it will be so before all content of this lazy sliver will be created. Then precedingScrollExtent will stop being infinite.</p><p><strong><em>remainingPaintExtent</em></strong></p><p>The number of pixels of content that the sliver should consider providing. Providing more pixels than this is inefficient.</p><p>But it is just considering, the actual number of pixels is specified in the SliverGeometry.</p><p>While the sliver is in the visible part of the viewport, this param is a distance from the leading edge of the sliver to the trailing edge of the viewport.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*pTvxpbf3X5gogPkL-k9eFQ.png" /></figure><p>And when the leading edge of the sliver will leave the visible part of the viewport, this property will be equal to viewportMainAxisExtent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*s09XmWC7CS27E6YM89cGUA.png" /></figure><p>When a sliver is before the visible part this value is 0 also.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*l8innRuqdPqSdX8jX9pNNw.png" /></figure><p>This value can be infinite when the viewport is unconstrained e.g. RenderShrinkWrappingViewport.</p><p><strong><em>remainingCacheExtent</em></strong></p><p>This one is identical to the previous one, except the borders for the measuring are not visible part edges but the cache area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*FISRuUiqMhZiHq_okR39BA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*6jbavzwSkMJEtd3_vj6hbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*PPUEUvMkVh3ZIeEgNrZIDQ.png" /></figure><p><strong><em>cacheOrigin</em></strong></p><p>Where the cache area starts relative to the scrollOffset.</p><p>The cacheOrigin is always negative or zero and will never exceed the cacheExtent absolute value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*gkOuhqA2bRr7Dog5cfjgLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*jn5rOJJkHvHxKL87uZCo3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*1VtJwyjSEggQAsH1L8mTOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*tE70c684TU4kCe_jW4Cfcg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*4jpJRO9_Y7tIRENXY2-Y0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*w_53ljWe6Udh2tdTc_9tPA.png" /></figure><p><strong><em>overlap</em></strong></p><p>Size between the first painted pixels of the sliver and the first not covered by previous sliver pixels. It uses for pinned or floating effects, e. g. SliverAppBar.</p><p>Let’s explore how the overlap changes in various positions on a simple case with a floating app bar (blue one in the picture).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*zUkT6RcwHjh0UMyrFEZqjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*8to41n9-N6pzeUgjAwWjeA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*i89lGRK7bC2MDQJ_yu9Qzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*IMyNHzrGQhTntRYv8rIKpA.png" /></figure><p>This value can be negative, for example with the BouncingScrollPhysics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*hFpLJER70huINdpoaSoK_g.png" /></figure><h3>SliverGeometry</h3><p>We have talked about constraints, but using them we should decide which is the size, and the size is the SliverGeometry.</p><p>SliverGeometry describes the amount of space occupied by a RenderSliver as the documentation says to us. And it has a lot of properties.</p><p>Let’s talk through them.</p><p><strong><em>visible</em></strong></p><p>Whether this sliver should be painted.</p><p>It’s pretty simple — if we set false, Flutter will not paint this sliver whenever it is.</p><p><strong><em>scrollExtent</em></strong></p><p>The estimated total scrollable extent that this sliver has content for. A simple way to say it: this is the amount of scrolling the user needs to do to get from the beginning of this sliver to the end of this sliver.</p><p>This property is used to calculate an offset for all other slivers, for this reason, we should set this property every time even this sliver is out of the vision.</p><p>In common cases, scrollExtent is permanent for the sliver all the time, but paintExtent or layoutExtent will change from 0 to scrollExtent while the sliver changes the position.</p><p><strong><em>paintExtent</em></strong></p><p>The amount of currently visible visual space that was taken by the sliver to render. It can take all SliverConstraints.remainingPaintExtent or its part. It means that the value of paintExtent must be between 0 and remainingPaintExtent.</p><p>This value does not affect how the next sliver is positioned. For example, if the paintExtent is 100 and layoutExtent is 0, for common slivers after this sliver it means they will be painted over in these 100 pixels. Based on this fact, it is easy to get that paintExtent affects the calculation of the SliverConstraints.overlap for the next sliver.</p><p><strong><em>layoutExtent</em></strong></p><p>The distance from the first visible part of this sliver to the first visible part of the next sliver, assuming the next sliver’s SliverConstraints.scrollOffset is zero.</p><p>This must be between zero and paintExtent and usually by default it’s paintExtent.</p><p><strong><em>cacheExtent</em></strong></p><p>How many pixels the sliver has consumed in the SliverConstraints.remainingCacheExtent.</p><p>This value should be equal to or larger than the layoutExtent because the sliver always consumes at least the layoutExtent from the SliverConstraints.remainingCacheExtent and possibly more if it falls into the cache area of the viewport.</p><p><strong><em>maxPaintExtent</em></strong></p><p>The estimated total paint extent that this sliver would be able to provide if the SliverConstraints.remainingPaintExtent was infinite.</p><p>This is used by viewports that implement shrink-wrapping.</p><p>By definition, this cannot be less than paintExtent.</p><p><strong><em>paintOrigin</em></strong></p><p>The visual location of the first visible part of this sliver relative to its layout position.</p><p>The default value is 0, which means slivers start painting at their layout position by default.</p><p>If we set this negative, the sliver starts to paint earlier and be painted under the previous one. If we set this positive, the sliver starts to paint later and be painted over the next one.</p><p>It does not affect the position of other slivers, but affects the SliverConstraints.overlap for the next.</p><p><strong><em>hitTestExtent</em></strong></p><p>The distance from where this sliver started painting to the bottom of where it should accept the user’s interaction.</p><p>This must be valued between zero and paintExtent. And by default, it is paintExtent because we expect that all visible parts are usually interactive</p><p><strong><em>maxScrollObstructionExtent</em></strong></p><p>The maximum extent by which this sliver can reduce the area in which content can scroll if the sliver were pinned at the edge, for example, SliverAppBar with pinned = true.</p><p>Slivers that never get pinned at the edge, should return zero.</p><p><strong><em>scrollOffsetCorrection</em></strong></p><p>The value for correction of the scroll by a parent. If this is non-zero after RenderSliver.performLayout returns, the scroll offset will be adjusted by the parent and then the entire layout of the parent will be rerun.</p><p>If the parent is also a RenderSliver, it must propagate this value in its own RenderSliver.geometry property until the viewport, which will adjust offset based on this value.</p><p>For example, it can be used for Cupertino refresh, which takes some size, but while it’s disappearing the size is changing. And this change of course affects the following slivers. ScrollOffsetCorrection is used to fix it.</p><p><strong><em>hasVisualOverflow</em></strong></p><p>Whether this sliver has a visual overflow.</p><p>By default, this is false, which means the viewport does not need to clip its children. The viewport will apply a clip to its children if any slivers have a visual overflow.</p><h3>Conclusion</h3><p>We’ve explored all that we need to know about Slivers. Hope this knowledge will help you to do the most exciting implementations of scroll behavior. If you like this topic, I advise you also check my <a href="https://medium.com/@mbixjkee1392/c449a1557038">next article</a>, where I’ll put all this knowledge into practice to get custom behavior for leaving the screen.</p><p>Stay on the 🎯 Dart side of the Force ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6082f2c6b57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Under the Hood: Owners]]></title>
            <link>https://medium.com/@mbixjkee1392/flutter-under-the-hood-owners-2ec741d45bea?source=rss-8bfe0fa05e74------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ec741d45bea</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Mikhail <mbixjkee> Zotyev]]></dc:creator>
            <pubDate>Tue, 10 May 2022 20:20:31 GMT</pubDate>
            <atom:updated>2022-09-02T07:41:53.322Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello! My name is Mikhail Zotyev, I’m the Flutter Department TechLead at Surf. And this is the last part of my article series about how Flutter works under the hood:</p><ol><li><a href="https://medium.com/surfstudio/flutter-under-the-hood-401503d2979e"><strong>Flutter Under the Hood</strong></a></li><li><a href="https://medium.com/surfstudio/flutter-under-the-hood-binding-2b0ea65e5314"><strong>Flutter Under the Hood: Binding</strong></a></li><li><strong>Flutter Under the Hood: Owners</strong> (you are here)</li></ol><p>Give you a little piece of advice — for better understanding, read these articles one by one, because all of these parts tell about one of the important internal aspects of the Flutter work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*OKqEvZbZlN_k4cxEl0sw3g.png" /></figure><h3>Frame building</h3><p>In the first part, we talked about the interaction between <em>Widgets</em>, <em>Elements</em>, and <em>RenderObjects</em>. But I have described this more simply than they are: getting a new widget tree was in the moment, and all <em>RenderObject</em> properties changed also. But these processes are a little more complicated.</p><p>The first thing we have to know for understanding the real process is how Flutter builds the frame. The Engine asks <em>SchedulerBinding</em> to prepare a new frame.</p><p><em>SchedulerBinding’s</em> workflow has a few stages named <em>SchedulerPhases</em>.</p><p><strong>Idle.</strong> No frame is being processed in this phase. But various tasks, microtasks, etc. may be executed in this phase.</p><p><strong>TransientCallbacks.</strong> In this phase, transient callbacks are called. Typically, these callbacks are used for animation updates.</p><p><strong>MidFrameMicrotasks.</strong> Microtasks scheduled during the processing of transient callbacks are currently executing.</p><p><strong>PersistentCallbacks.</strong> The persistent callbacks are currently executing. Typically, these are used for the build, layout, and paint pipelines.</p><p><strong>PostFrameCallbacks.</strong> The post-frame callbacks are currently executing. Typically, these are used for the next frame’s work.</p><p>Four phases of these, except the idle, are used to build a new frame. It completes in ten steps:</p><ol><li><strong>Animation step.</strong> Calling <em>handleBeginFrame</em> starts a procession of all callbacks which are registered in <em>scheduleFrameCallback</em> in the registration order. The most common of them are <em>Tickers</em> for <em>AnimationControllers</em>. And all active animations take updates this way. Why is this step very first? This is pretty simple — for most next steps we need to have actual changes by playing animations. And without it, we can’t make the layout right.</li><li><strong>Microtasks step.</strong> After <em>handleBeginFrame</em> ends, all scheduled microtasks start.</li><li><strong>Build step.</strong> All <em>Elements</em> which are marked as needing updates, rebuild in this step.</li><li><strong>Layout step.</strong> All the dirty <em>RenderObjects</em> have updates in this step. Also, we detect in this step, which <em>RenderObjects</em> need to repaint.</li><li><strong>Composition bits step.</strong> The compositing bits on any dirty <em>RenderObjects</em> are updated.</li><li><strong>Paint step.</strong> All <em>RenderObjects</em> which are marked as needing paint, are repainted in this step. After this layer tree is generated.</li><li><strong>Composition step.</strong> The layer tree is turned into a <em>Scene</em> (a special object that describes what we need to see) and sent to the GPU.</li><li><strong>Semantic step.</strong> All dirty render objects have updates for their semantic properties. Then a semantic tree builds. The semantic tree is used by the engine to help people within system assistive technology.</li><li><strong>Widgets layer finalization step.</strong> The widget tree is finalized by this step. All unused states and elements will be disposed of.</li><li><strong>Scheduler finalization step.</strong> In this step, all callbacks registered by <em>addPostFrameCallback</em> are invoked.</li></ol><p>After all these steps we have the frame completed. But anyway, who makes all these things? The biggest part of the work is made by two manager objects.</p><h3>BuildOwner</h3><p>BuildOwner manages builds, updates, and all internal work with the element tree. Its responsibilities in the <strong>Build</strong> and the <strong>Widgets layer finalization</strong> steps.</p><p>In order to manage the building tree, <em>BuildOwner</em> needs a list of elements that are marked as needed to update. <em>BuildOwner</em> stores this list inside.</p><p>Let’s look at the methods which help <em>BuildOwner</em> to make this work.</p><p><em>scheduleBuildFor: </em>make it possible to mark elements as needed to update and put this element to the dirty elements list so that it will be updated.</p><p><em>lockState: </em>the mechanism which protects elements from wrong using, for example, mark as dirty while disposing of.</p><p><em>buildScope: </em>establishes a scope for updating the widget tree. It uses dirty elements for this in the order of depth.</p><p><em>finalizeTree: </em>finalize tree building. Destroy all elements that are no longer active. In debug mode, Flutter makes additional checking, for example checking duplicate global keys.</p><p><em>reassemble: </em>This is the working horse of the HotReload mechanism. HotReload makes it possible to avoid recompiling applications again and again when we make changes and just send a new version of code to the VM.</p><p>All these methods of course use in match with then ten steps which we describe earlier. Let’s confirm this. We can see it in the <em>WidgetsBinding.drawFrame</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43d72964e2fb633b9283a1af306c9e68/href">https://medium.com/media/43d72964e2fb633b9283a1af306c9e68/href</a></iframe><p>As we can see, the buildScope for <strong>Build step</strong> and the finalizeTree for <strong>Widgets layer finalization step.</strong> Between there we see the <em>super.drawFrame</em>, but about this, we will talk a little bit later, when we’ll look to another manager.</p><p>In order to put it all together, we needed to leave the <em>BuildOwner </em>for a few minutes<em>.</em> Let’s look at the <em>Element.rebuild</em> method. When is it called? Just three ways for this:</p><ol><li>By the <em>BuildOwner</em> when the tree builds.</li><li>By the <em>ComponentElement</em> when it first time inflates to the tree. A first-time build is required for this case, because the <em>ComponentElement</em> just describes the part of UI, and uses other widgets for this.</li><li>And the last one is when <em>ComponentElement</em> has an update.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/0*KgdVrH4D_l1ywyaw" /></figure><p>The <em>rebuild</em> calls <em>perfomRebuild</em> and this one method is more interesting because it has different implementations for different elements.</p><p>For the <em>RenderObjectElements</em> it initiates a <em>RenderObject</em> update. For the <em>ComponentElement</em> it calls a <em>build</em> method. Yep, actually, that <em>build</em> method, which the <em>State</em> and the <em>StatelessElement</em> have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/0*PgVzZPYqwySjnyrV" /></figure><p>Let’s recall what this method does. It returns the widget, which we send to the <em>Element.updateChild</em>. There this widget will be mounted or updated with the current element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/0*yExNfNaulyg4cW6y" /></figure><p>As far as good, we close this scheme, except one way — <em>BuildOwner.buildScope.</em></p><p>In this case, we commonly call rebuild on all elements which are marked as dirty. We remember that to make an element dirty, we can use the calling <em>scheduleBuildFor</em>. There are not a lot of cases that lead to this:</p><ol><li>Reactivate the element from the deactivated state.</li><li>At the start of the application, when attached to the render tree.</li><li>By calling <em>setState</em> in the State.</li><li>By using <em>HotReload.</em></li><li>And when dependencies did change (using <em>InheritedElement).</em></li></ol><p>Now we join all puzzles together — this is how <em>BuildOwner</em> works.</p><h3>PipelineOwner</h3><p>Another one manager takes a part in the preparation of the frame is the <em>PipelineOwner</em>. Its responsibility — working with the rendering pipeline. As we remember it works from 4 to 8 steps in our list. And <em>WidgetsBinding.drawFrame</em> confirms for us it again.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43d72964e2fb633b9283a1af306c9e68/href">https://medium.com/media/43d72964e2fb633b9283a1af306c9e68/href</a></iframe><p>What is the <em>super.drawFrame</em>? Because the <em>WidgetsFlutterBinding</em> is a composition of other bindings, this method leads us to the <em>RendererBinding.drawFrame.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cac358eb600a9476e581954306451bf/href">https://medium.com/media/0cac358eb600a9476e581954306451bf/href</a></iframe><p>As we can see in the code, calling the PipelineOwner’s methods, define the order of the frame preparation steps:</p><ul><li>flushLayout for the <strong>Layout step</strong>;</li><li>flushCompositingBits for the <strong>Composition bits step</strong>;</li><li>flushPaint for the <strong>Paint step</strong>;</li><li>flushSemantics for the <strong>Semantic step.</strong></li></ul><p>Also as the <em>BuildOwner</em>, <em>PipelineOwner</em> stores inside the list of objects which needs to update. But in the <em>PipelineOwner</em> case, these objects are RenderObjects. They are added to this list when their property has updates. Commonly <em>updateRenderObject</em> called for the actualization of current properties, and if the new value is not the same as the previous, this RenderObject is added to the list.</p><p>Let’s look at the methods of the <em>PipelineOwner</em>, and what they do.</p><p><em>flushLayout: </em>all <em>RenderObject</em> that mark needs to layout will be processed. The layout will be recalculated and the <em>RenderObject</em> will mark as needed to repaint.</p><p><em>flushCompositingBits: </em>the same as previous but for special <em>RenderObjects</em> which take a part in composition directly.</p><blockquote>After calling these two methods, all RenderObjects which need to be repainted will be defined.</blockquote><p><em>flushPaint: </em>this method repaints all objects which we mark as needed to repaint.</p><p>The method <em>compositeFrame</em> will be called on the root of the render tree at the end of the process. This will prepare the <em>Scene</em> object and send this scene to the engine for showing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c288c8bfe7c4050b1f6607c0389920bf/href">https://medium.com/media/c288c8bfe7c4050b1f6607c0389920bf/href</a></iframe><h3>Layout algorithm</h3><p>The important feature of layout building is how the algorithm works.</p><p>When we have a lot of objects which we need to process, we must have an effective algorithm. Flutter aims for linear performance for the initial layout and <em>sublinear layout performance</em> in the common case of subsequently updating an existing layout. It means that the amount of time spent on the layout should scale more slowly than the number of <em>RenderObjects</em>.</p><p>The layout builds once per frame, as you could notice. All objects used in this process handle twice: going down by the tree and going up. Some parts of the layout are more complex and need more iteration, but this is the exclusion rather than the rule.</p><p>In order to guarantee this performance, Flutter uses next rules:</p><ol><li>Constraints go down, from parent to the children.</li><li>Sizes go up, from children to the parent.</li><li>Parents position their children.</li></ol><p>Summarize this — only info from parents to the child is a constraint, and only info from child to parent is a size. But straightforward counting is not very effective, because of it Flutter has tricky optimization:</p><ol><li>If the child object didn’t mark its own layout as needed to update, he will not recalculate while getting the same constraints.</li><li>Every time when the parent calls the layout method on the child, it declares — would the size be used in its own calculation.</li><li>Every time when a parent calls the layout method on a child object, the parent indicates whether it uses the size information returned by the child object. It often happens that the parent does not use this information. This means it doesn’t have to recalculate its size even if the child changes its size. It is guaranteed that the new size will comply with the existing restrictions.</li><li>Tight constraints are those limits that only one allowed size can satisfy. If the maximum and minimum heights are equal, and the maximum and minimum widths are also identical, the only appropriate size is that width and height. In the case of setting tight constraints, the parent should not recalculate its size when the child recalculates its own. Even if the parent uses the child’s size in its layout because the child can’t resize without new constraints from the parent.</li><li>A <em>RenderObject</em> may declare that it uses only the constraints provided by the parent to calculate its size. This means that the parent object of this render object does not need to be recomputed ever, except when the constraints are updated.</li></ol><h3>Conclusion</h3><p>The good performance of the Flutter is not random. It is guaranteed by a complex and smart underhood mechanism.</p><p>I hope after this article series you clearly understand how Flutter works under the hood, and this knowledge helps you write efficient and high-performance code, and find elegant solutions for all problems.</p><p>Thank you for your time! Stay at the Dart side!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ec741d45bea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Under the Hood: Binding]]></title>
            <link>https://medium.com/@mbixjkee1392/flutter-under-the-hood-binding-2b0ea65e5314?source=rss-8bfe0fa05e74------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b0ea65e5314</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Mikhail <mbixjkee> Zotyev]]></dc:creator>
            <pubDate>Fri, 28 Aug 2020 15:28:40 GMT</pubDate>
            <atom:updated>2022-05-22T10:35:36.277Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the part of my article series about how Flutter works under the hood:</p><ol><li><a href="https://medium.com/surfstudio/flutter-under-the-hood-401503d2979e"><strong>Flutter Under the Hood</strong></a></li><li><strong>Flutter Under the Hood: Binding</strong> (you are here)</li><li><a href="https://medium.com/@mbixjkee1392/flutter-under-the-hood-owners-2ec741d45bea"><strong>Flutter Under the Hood: Owners</strong></a></li></ol><p>I recommend you read through it first or refresh it in your memory for a better understanding. In it, I have analyzed one of the key aspects of Flutter — the interaction between trees and distribution of responsibilities among them. However, the question remains: how do you ensure its functionality? This is what we will be focusing on in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*9igTNxeY98TO7YO-0TYqww.png" /></figure><h3>Overview</h3><p>If you open <a href="https://flutter.dev/docs/resources/technical-overview">the technical overview of Flutter</a>, you will find this scheme. It shows a series of layers in which the creators of Flutter organized the framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/0*nzrJJOC3w_XKKywk" /></figure><p>They call it layer cake which is a very precise description. It consists of larger and smaller layers.</p><p><strong>The framework level</strong> contains everything we use when writing apps, including all service classes which allow the code to interact with the lower engine layers. Everything inside this level is written in Dart.</p><p><strong>The engine level</strong> is positioned lower than the framework level. It contains classes and libraries that ensure the functioning of the framework level, including Dart virtual machine, Skia etc.</p><p><strong>The platform level</strong> contains mechanisms related to a specific launch platform.</p><p>Let us take a closer look at the framework level. In the diagram, it is depicted as layers arranged from higher-level to lower-level ones. At the very bottom, we see the <em>Foundation</em> layer. As the name suggests, this layer is something fundamental and basic that is located at the framework level. Here is what stands in the description of this library:</p><blockquote>Core Flutter framework primitives.</blockquote><blockquote>The features defined in this library are the lowest-level utility classes and functions used by all the other layers of the Flutter framework.</blockquote><p>Among other things, this library also contains <a href="https://api.flutter.dev/flutter/foundation/BindingBase-class.html">BindingBase</a> which is the base class for all Bindings.</p><p>Binding</p><p>First, let us take a look at what Binding stands for and how it is used in Flutter. As evidenced by its name, Binding has to do with some kind of connection. The documentation on BaseBinding states:</p><blockquote>Base class for mixins that provide singleton services (also known as «bindings»). To use this class in an `on` clause of a mixin, inherit from it and implement [initInstances()]. The mixin is guaranteed to only be constructed once in the lifetime of the app (more precisely, it will assert if constructed twice in checked mode).</blockquote><p><em>BaseBinding</em> is an abstract base class. Let us list some of the specific implementations of bindings.</p><p><strong>ServicesBinding</strong> listens for platform messages and directs them to the handler for incoming messages (BinaryMessenger).</p><p><strong>PaintingBinding</strong> is responsible for binding to the painting library.</p><p><strong>RenderBinding</strong> binds the render tree to the Flutter engine.</p><p><strong>WidgetBinding</strong> binds the widget tree to the Flutter engine.</p><p><strong>SchedulerBinding</strong> is the scheduler for running immediate tasks such as:</p><ul><li>transient callbacks which are triggered by the system’s Window.onBeginFrame callback (for example, Ticker and AnimationController events)</li><li>persistent callbacks, triggered by the system’s Window.onDrawFrame callback (for instance, events for updating the system’s display after transient callbacks have executed)</li><li>post-frame callbacks which are run after persistent callbacks, just before returning from Window.onDrawFrame</li><li>non-rendering tasks to be run between frames.</li></ul><p><strong>SemanticsBinding</strong> binds the semantics layer and the Flutter engine.</p><p><strong>GestureBinding</strong> is a binding for the gesture subsystem.</p><p>Binding is, essentially, the glue between the engine level and the framework level of Flutter. Each of them is responsible for a specific line of work.</p><h3>WidgetsFlutterBinding</h3><p>To better understand how it all works together, let us look at the starting point for any Flutter app, namely calling runApp. The method we call for is located in the <em>binding.dart</em>, and for a good reason. Its description says that it Inflates the given widget and attaches it to the screen. It works like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdb07d9a556eef006d717c7fcad7865e/href">https://medium.com/media/bdb07d9a556eef006d717c7fcad7865e/href</a></iframe><p>We came across <em>WidgetsFlutterBinding</em> here. It is an implementation of a concrete binding for apps based on the Widgets framework. This is, essentially, the glue that binds the framework to the Flutter engine. <em>WidgetsFlutterBinding</em> consists of multiple bindings that we have already mentioned: <em>GestureBinding</em>, <em>ServicesBinding</em>, <em>SchedulerBinding</em>, <em>PaintingBinding</em>, <em>SemanticsBinding</em>, <em>RendererBinding</em>, <em>WidgetsBinding</em>. All of them form a layer able to bind our app to the Flutter engine in all directions.</p><p>Going back to launching the app. <em>WidgetsFlutterBinding</em> calls the <em>scheduleAttachRootWidget</em> and <em>scheduleWarmUpFrame</em> methods. Let us see what happens there.</p><h3>ScheduleAttachRootWidget</h3><p>The <em>scheduleAttachRootWidget </em>method is a scheduled implementation of <em>attachRootWidget</em>. This method belongs to <em>WidgetsBinding</em>. Its description reads that it attaches the given widget to renderViewElement which is a root element of the element tree.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1e061a6b16211a71e8abe1525f7b05d/href">https://medium.com/media/e1e061a6b16211a71e8abe1525f7b05d/href</a></iframe><p>As we can see from the code, this method creates RenderObjectToWidgetAdapter which is the root widget of the widget tree that acts as a bridge between the trees. If we look at its implementation, we will notice that it does not create RenderObject for itself but returns a value from the container field instead, where we pass renderView from RendererBinding to. This renderView is the root element of the render tree.</p><p><em>RenderView get renderView =&gt; _pipelineOwner.rootNode;</em></p><p>PipelineOwner is a manager that is responsible for the rendering pipeline.</p><p>Let us go back to the <em>attachRootWidget</em> method. The created adapter calls the attachToRenderTree method which is used to create the root of the element tree for the first time. Note that <em>buildOwner</em> is passed to the <em>attachToRenderTree</em> method. This is the manager class for the widgets framework. It tracks the state of widgets as well as which widgets need rebuilding, and has a number of other important tasks related to updating the state of the widget tree. This way we get the three Flutter trees, and each of them is stored and managed using Bindings.</p><h3>ScheduleWarmUpFrame</h3><p>The <em>scheduleWarmUpFrame </em>method belongs to <em>SchedulerBinding</em> and is used to schedule a frame to run as soon as possible, rather than waiting for a system “Vsync” signal. Since this method is used while the app is running, the first frame — which is likely to be expensive — gets some extra time to run. ScheduleWarmUpFrame locks events dispatching until the scheduled frame has completed.</p><p>As we can see, both mechanisms that have been launched at the start relate to and interact with different Bindings which are closely connected and provide interaction with the system. Let us sum up with this diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*yUPXeUH1H8zmbRYM" /></figure><h3>Conclusion</h3><p>Bindings is an essential mechanism for organizing work of a Flutter app. It links together various aspects of the app and connects them to the engine.</p><p>At the same time, it allows us to write apps on the highest-level part of the framework, without having to worry about organizing the rest in a coherent manner. I hope that this article helps you navigate through this segment of the Flutter framework. Stay safe!</p><p><strong>References</strong></p><p><em>Flutter</em></p><p><a href="https://flutter.dev/"><em>https://flutter.dev/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b0ea65e5314" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSL Pinning in Flutter Apps]]></title>
            <link>https://medium.com/@mbixjkee1392/ssl-pinning-in-flutter-apps-254e01e57965?source=rss-8bfe0fa05e74------2</link>
            <guid isPermaLink="false">https://medium.com/p/254e01e57965</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ssl-pinning]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Mikhail <mbixjkee> Zotyev]]></dc:creator>
            <pubDate>Thu, 18 Jun 2020 12:14:50 GMT</pubDate>
            <atom:updated>2022-09-09T14:23:16.414Z</atom:updated>
            <content:encoded><![CDATA[<p>For most mobile apps there comes a time to roll them out. If you have not yet tended to minimal protection from attacks, this issue will get the more acute the closer the app’s launch.</p><p>It is crucial to protect your users against a very common attack called MITM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Cn9V_Dm9ZKcJTPhYFdcAA.png" /></figure><h3>MITM</h3><p><strong>Man-in-the-middle attack</strong>, also known as <strong>hijack attack</strong>, is an attack where the intruder secretly relays and sometimes alters the communications between two parties who believe that they are directly communicating with each other. It is a way to compromise the communication channel where the hacker interferes with the transmission protocol by accessing the channel between these parties in order to delete or distort information.</p><p>The HTTP protocol was vulnerable to this attack to begin with, therefore a secure version of the protocol was created in order to fix this issue. It uses <a href="https://developer.mozilla.org/en-US/docs/Glossary/SSL">SSL</a> or <a href="https://developer.mozilla.org/en-US/docs/Glossary/TLS">TLS</a> to encrypt the connection between a client and a server: the server sends its certificate to the client for identification. The X.509 certificate is a file that contains the following information:</p><ul><li>Name</li><li>Public key</li><li>Serial number</li><li>Signature algorithm</li><li>Digital signature</li></ul><p>The identification process requires that:</p><ol><li>The server name must precisely match the name given in the certificate, otherwise the certificate may be considered compromised.</li><li>The SSL certificate chain can be traced from a private SSL certificate through intermediate certificates to the root certificate of a trusted certificate authority.</li></ol><p>Let us look at the second point more closely.</p><p>It would be impossible to install each certificate separately, there are too many of them. Thus, the following certificate management system comes into play. Since certificates are basically server identities, they do not appear on their own — they are issued by certificate authorities. The CA certificates, also known as root certificates, play the most significant role. CAs are publicly available and their keys are trusted by default. They are usually embedded in the operating system and get updated alongside with it. Certificates operate in a strict hierarchy. CA certificates can sign other certificates which in turn sign next-level certificates etc. If a certificate is compromised, it can be revoked together with its child certificates.</p><p>It seems fairly secure but what if the user compromises the certificate storage on their system by installing the intruder’s certificate?</p><h3>SSL-pinning</h3><p><strong>SSL-pinning</strong> allows you to pin a server’s key or a public key to the client. One of the most efficient ways to achieve this in mobile apps is embedding a trusted SSL certificate. This way we ignore the system storage and can manually specify which certificate is trustworthy. This method comes in handy when it is necessary to use a self-signed certificate without having the end user install it.</p><h3>SSL-pinning in Dart</h3><p>Dart uses the <em>HttpClient</em> class, namely, its private standard implementation to send http requests. Whether the connection is secure or not is determined based on the addressing scheme of the website.</p><p><em>bool isSecure = (uri.scheme == «https»);</em></p><p>If secure connection is available, <em>SecureSocket</em> will attempt to establish a secure connection. In case of failure we will get notified that the connection uses a compromised certificate if we had previously registered a function that would handle this.</p><p>This function can be registered using <em>badCertificateCallback</em> in <em>HttpClient</em>. Apart from letting us know that the certificate is compromised, the function can also handle this issue. At this point we have to decide whether we continue with this request or not.</p><p>If we do not add a handler, the connection will be terminated following the certificate verification failure.</p><p>How does <em>SecureSocket</em> verify certificates? The standard behavior in this case would be to check for certificates registered in the system. But, as we have said before, this would not be the best approach for a reliable verification. Being able to verify a specific certificate or a certificate chain is crucial here.</p><p>In Dart, the <em>SecurityContext</em> class can solve this issue. As stated in the description of this class, it is an object that contains certificates to trust when making a secure client connection as well as the certificate chain and private key to serve from a secure server. This object can be passed on to <em>HttpClient</em> upon its creation. In this case, the client will rely on the data stored in the context for verification regardless of whether or not the system trusts these certificates.</p><p><em>SecurityContext</em> can be created using various constructors, therefore the contents will differ depending on the constructor. For instance, the default constructor creates a completely empty context without any registered keys.</p><p>But if we take <em>SecurityContext.defaultContext</em>, it creates a context containing some sets of trusted certificates depending on the system. On Windows or Linux, the Mozilla Firefox certificate storage is used. In case with MacOS, iOS and Android only those certificates get registered that the system considers trustworthy.</p><p>In addition, the context contains methods for registering private keys, trusted certificates and certificate chains.</p><p>In order to register a trusted certificate, you can choose one of two methods.</p><pre><em>void setTrustedCertificates(String file, {String password});</em></pre><p>This method allows you to specify the path to the certificate.</p><pre><em>void setTrustedCertificatesBytes(List&lt;int&gt; certBytes, {String password});</em></pre><p>It uses the certificate content as bytecode for registration.</p><p>In my opinion, it is better to use <em>setTrustedCertificatesBytes</em>, and the developers actually warn us:</p><blockquote>NB: This function calls [File.readAsBytesSync], and will block on file IO. Prefer using [setTrustedCertificatesBytes].</blockquote><p>The reason behind this is quite simple. If some ill-wisher wanted to harm us, it would require a great deal of effort. We cannot just put the certificate file in the resources as a regular file, it is easy to find and replace by decompiling. Although the attacker will not be able to sign the rebuilt app, no one can do more harm to the user than the user themselves. Therefore, the inability to re-sign an app using the same keys may not be a decisive factor.</p><p>What if we build the key into the app as bytecode? Since Flutter uses AOT compilation when building apps in release mode, it will make things quite difficult for anyone who wants to replace the certificate by cracking the app.</p><h3>Practical implementation of SSL-pinning</h3><p>First of all, in order to establish a trusted connection you will require the certificate file used by the server. If you cannot contact the system administrators or if you are short on time, it is easy to obtain it using a browser. In this example, I will use Google Chrome but you can do this in other browsers as well.</p><p>Let us go to the address which certificate we want to obtain. For instance, <a href="https://www.facebook.com/">www.facebook.com</a>. If the connection is secure, we will see a padlock icon in the address bar. Clicking on it will open information about the connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/0*aCRHTF1ajKVMY4bL" /></figure><p>We are interested in the certificate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*JHjTxjHBv2alzVoaVJOESg.png" /></figure><p>We can find a certificate chain in the window that pops up. The last certificate is the one belonging to the resource.</p><p>You can save the certificate by dragging it to any folder on your computer.</p><p>Here is another way to obtain the same file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/0*sjg87G1lcwsQ8tV_" /></figure><p>When in developer tools, go to the Security tab. Clicking on View Certificate opens a familiar certificate view window. You can save the file from here.</p><p>The certificate file gets the <em>.cer</em> suffix which is one of possible representations of this file. One and the same certificate can be represented in various formats which determine how the certificate data are encoded etc. Consulting the documentation for methods of adding a certificate to trusted certificates in <em>SecurityContext</em> will reveal that we need a specific certificate format, either <strong>PEM </strong>or <strong>PKCS12</strong>.</p><p>The <em>.cer</em> suffix for certificates can be used in two formats: PEM and DER. Only one of them meets our requirements. In order to determine which format we are dealing with, we have to open the certificate in a text editor and look at its contents. If the code starts with the tag <strong>BEGIN CERTIFICATE</strong> and ends with <strong>END CERTIFICATE</strong>, it means it is <em>PEM</em>. If we see a binary file in the text format, we are looking at <em>DER</em>.</p><p>You can convert the file if you need to, there are plenty of converters to choose from. I will demonstrate one of the ways you can do that.</p><p>Open the command line and run the following command at the level of the certificate:</p><p><em>openssl x509 -inform der -in certificate.cer -out certificate.pem</em></p><p><em>Certificate.cer</em> is the name of the certificate that is being converted and <em>certificate.pem</em> is the certificate’s name after conversion.</p><p>Now we have a certificate in the format that suits us. We have to read it as bytes and save this value for future use in the app. List is pretty good for storing this data. For more convenience, I wrote a short script that reads the certificate as bytes and creates a Dart file with a variable storing this value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f40deff1717fa2bf78cfceb7b9454076/href">https://medium.com/media/f40deff1717fa2bf78cfceb7b9454076/href</a></iframe><p>Now we just have to copy this file to the project. Using it will be fairly easy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42a2e35ad731746113632d8d1329fabf/href">https://medium.com/media/42a2e35ad731746113632d8d1329fabf/href</a></iframe><p>If we go to this address and the certificate provided during verification does not match the one we built into the app, the <em>HandshakeException</em> error will appear.</p><p>I hope that this article helps you better protect your users against these attacks. Stay safe!</p><h4>References</h4><p><a href="https://en.wikipedia.org/wiki/Man-in-the-middle_attack">Man-in-the-middle attack<br></a><a href="https://www.emaro-ssl.ru/blog/convert-ssl-certificate-formats/">SSL certificate formats: how to convert certificate to .PEM, .CER, .CRT, .DER, PKCS or PFX (Russian)</a></p><p><a href="https://developer.mozilla.org/en-US/">MDN</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=254e01e57965" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Under the Hood]]></title>
            <link>https://medium.com/@mbixjkee1392/flutter-under-the-hood-401503d2979e?source=rss-8bfe0fa05e74------2</link>
            <guid isPermaLink="false">https://medium.com/p/401503d2979e</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Mikhail <mbixjkee> Zotyev]]></dc:creator>
            <pubDate>Fri, 29 May 2020 12:12:36 GMT</pubDate>
            <atom:updated>2022-08-29T09:50:41.567Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello! My name is Mikhail Zotyev, I am a Tech Lead Flutter team at <a href="http://surf.dev/?utm_source=medium&amp;utm_medium=article&amp;utm_campaign=flutter-under-the-hood">Surf</a>. I have been with Flutter for almost 2 years and during this time I managed to appreciate and feel its various qualities. It is friendly — you can easily and quickly get used to Flutter if you have experience in any other direction. Personally, I came from game development. Flutter is flexible — it is a powerful framework that will allow you to solve various problems, including those of high complexity. And while it is flexible, it is not complicated, but on the contrary, very simple: with the help of a dozen basic widgets, you can assemble quite decent user interfaces. And the most interesting thing is that most likely you will be able to use it, at first without even thinking about the question: “How does it work at all?”</p><p>But in this article, we’ll go to the Dart side of this Force and analyze how Flutter works under the hood.</p><p>This is the first part of my article series about how Flutter works under the hood:</p><ol><li><strong>Flutter Under the Hood </strong>(you are here)</li><li><a href="https://medium.com/surfstudio/flutter-under-the-hood-binding-2b0ea65e5314"><strong>Flutter Under the Hood: Binding</strong></a></li><li><a href="https://medium.com/@mbixjkee1392/flutter-under-the-hood-owners-2ec741d45bea"><strong>Flutter Under the Hood: Owners</strong></a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fn8160WBEmQpVChJLvRMqg.png" /></figure><h3>Widget</h3><p>Flutter development team have been repeatedly telling us that <em>Flutter is all about widgets</em>. Let us see if this is true. First, let us take a look at the <strong>Widget</strong> class.</p><p>The first thing we see in the documentation for this class is:</p><blockquote>Describes the configuration for an [Element].</blockquote><p>Turns out, the widget itself is simply a description of a certain <strong>Element</strong>.</p><blockquote>Widgets are the central class hierarchy in the Flutter framework. A widget is an immutable description of part of a user interface. Widgets can be inflated into elements, which manage the underlying render tree.</blockquote><p>To sum up, <em>Flutter is all about widgets</em> is the bare minimum you need to know to be able to use Flutter. At the same time, it is surrounded by a number of additional mechanisms that serve the framework performance.</p><p>We also learned that:</p><ul><li>a widget is an immutable description of part of a user interface</li><li>a widget is associated with a certain extended representation called an element</li><li>an element controls some entity in render tree.</li></ul><p>You might have noticed something odd. Immutability and the user interface do not fit together very well. I would even say, they are incompatible. Keep that in mind, we will get back to it later. For now, let us get on with the widget documentation.</p><blockquote>Widgets themselves have no mutable state (all their fields must be final).<br>If you wish to associate mutable state with a widget, consider using a [StatefulWidget], which creates a [State] object (via [StatefulWidget.createState]) whenever it is inflated into an element and incorporated into the tree.</blockquote><p>This paragraph supplements the first point. That is, if we need a mutable configuration, we use a certain entity called <strong>State</strong> which describes the current state of this widget. The state, however, is associated not with widget itself but with its element representation.</p><blockquote>A given widget can be included in the tree zero or more times. In particular a given widget can be placed in the tree multiple times. Each time a widget is placed in the tree, it is inflated into an [Element], which means a widget that is incorporated into the tree multiple times will be inflated multiple times.</blockquote><p>Let us summarize what we know about widgets so far:</p><ul><li>A widget is a central class hierarchy.</li><li>A widget describes a configuration.</li><li>A widget is an immutable description of part of a user interface.</li><li>A widget is associated with an element which controls rendering.</li><li>Mutable state of a widget can be described by an entity that is associated with an element representing that widget and not with the widget itself.</li></ul><h3>Element</h3><p>What are those elements that handle everything? Let us see what we can find in documentation for the Element class.</p><blockquote>An instantiation of a [Widget] at a particular location in the tree.</blockquote><blockquote>Widgets describe how to configure a subtree but the same widget can be used to configure multiple subtrees simultaneously because widgets are immutable. An [Element] represents the use of a widget to configure a specific location in the tree. Over time, the widget associated with a given element can change, for example, if the parent widget rebuilds and creates a new widget for this location.</blockquote><p>Widgets describe how to configure a part of a user interface. But, as we already know, one and the same widget can be included in the tree multiple times at several locations. Each of these locations is represented by a corresponding element. A widget associated with an element may change over time. This means that elements are more resilient and continue to be used, needing only to update their associations.</p><p>This is a fairly rational solution. Widgets are an immutable configuration that simply describes a particular part of the interface, thus, they have to be pretty lightweight. Elements responsible for handling objects are significantly heavier and do not get rebuilt unless it is necessary.</p><p>In order to understand how it works, let us take a look at the element’s lifecycle:</p><ul><li>An element is created by calling Widget.createElement on the widget that will be used as the element’s initial configuration.</li><li>The mount method adds the newly created element to the tree at a given slot in a given parent. Calling this method also allows you to inflate any child widgets and attach elements to the render tree.</li><li>At this point, the widget is considered active and might appear on screen.</li><li>If the widget associated with an element is changed (e.g. its parent element is rebuilt), there are several possible scenarios. If the new widget has the same runtimeType and key as old widget, the element will be associated with the new widget. Alternatively, the current element is removed from the tree and a new element is created to be associated with the new widget.</li><li>In case the parent decides to remove a child or an intermediate ancestor, it will lead to removing that element’s render object from the render tree and adding it to the list of inactive elements, thus deactivating that element by calling deactivateChild.</li><li>Once an element is considered inactive, it will not appear on screen. An element can remain in the inactive state only until the end of the current frame. If it remains inactive at this point, the framework considers it defunct and this element will be unmounted.</li><li>If the element gets reincorporated into the tree (e.g., because it or one of its ancestors has a global key that is being reused), it will be removed from the owner’s list of inactive elements. The framework will call activate on the element, and reattach the element’s render object to the render tree. This means that the element might appear on screen again.</li></ul><p>As we can see from the class declaration, the element implements the BuildContext interface. BuildContext is an entity that handles the location of a widget in the widget tree, as stated in its documentation. It is almost identical to the element description. This interface is used to avoid direct manipulation of elements but at the same time give access to the necessary context methods. For example, the findRenderObject method that allows you to locate this element’s render object in the tree.</p><h3>RenderObject</h3><p>The last class we will look into is <strong>RenderObject</strong>. As the name implies, it is a render object. RenderObject has a parent as well as a slot where the parent can store child-specific data, for example, this object’s position. This object is responsible for implementing the basic layout and paint protocols.</p><p>RenderObject does not define a child model. It can consist of zero, one, or more children. On top of that, it does not define a coordinate system. You are free to choose from Cartesian coordinates, polar coordinates or whichever system that suits your needs. There are also no restrictions on layout protocols. You can decide either to adjust width and height of the layout, or constrain the size of the layout, or set the size and position of the child. If needed, the children can use their parent’s data.</p><h3>Putting it all together</h3><p>Let us summarize what we have learned so far to see how everything works together.</p><p>As we have established before, a widget is an immutable description whereas the user interface is far from being static. This discrepancy is removed by dividing the objects into three levels as well as dividing responsibilities:</p><ul><li>The widget tree declares configurations and stores properties.</li><li>The element tree handles lifecycle and arranges widgets into a hierarchy as well as associates render objects with widgets.</li><li>The render tree manages painting, sizes and constraints.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*Z1ZL6u1Lank8RDXK" /></figure><p>Let us see how these trees function on a simple example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*GTXKqNIZOA69oVjW" /></figure><p>Here we have the StatelessWidget containing some text, wrapped in the Padding widget.</p><p>Let us put ourselves in Flutter’s shoes for a moment. Say, we are given this particular widget tree.</p><p>Flutter: <em>Hey, Padding, I need your element.</em><br>Padding: <em>Sure thing, here’s SingleChildRenderObjectElement.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/0*VVljx4ycXjzDkJ_n" /></figure><p>Flutter:<em> That’s where you’ll be staying, element, make yourself at home.</em><br>SingleChildRenderObjectElement:<em> It’s all good, guys, but I need RenderObject.</em><br>Flutter:<em> Padding, how am I supposed to paint you?</em><br>Padding:<em> There you go, one RenderPadding, as requested.</em><br>SingleChildRenderObjectElement:<em> Great. I’m on it!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/0*jJrG9s3u2_dKRRdR" /></figure><p>Flutter:<em> Who’s next? StatelessWidget, now you give me an element.</em><br>StatelessWidget:<em> Here’s your StatelessElement.</em><br>Flutter:<em> StatelessElement, you’ll be subordinant to SingleChildRenderObjectElement. This is your desk, get to work.</em><br>StatelessElement:<em> Ok.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/0*v0stAX6dolxwMcg2" /></figure><p>Flutter:<em> RichText, may I see your element please?</em><br>RichText hands their MultiChildRenderObjectElement over. <br>Flutter: <em>MultiChildRenderObjectElement, here is your cubicle, get to work.</em><br>MultiChildRenderObjectElement:<em> I can’t work without a render.</em><br>Flutter:<em> RichText, we need a render object.</em><br>RichText:<em> Here’s RenderParagraph.</em><br>Flutter: <em>RenderParagraph, you’ll be receiving instructions from RenderPadding. MultiChildRenderObjectElement will be supervising your work.</em><br>MultiChildRenderObjectElement:<em> I’m all set now and ready to start.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/0*zU5tidknuswOQ9OJ" /></figure><p>You’re probably wondering why there isn’t a render object for StatelessWidget since we have stated that elements associate configurations with rendering? Let us take a closer look at the basic implementation of the mount method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cd331bb9953578ef46d02075323eb42/href">https://medium.com/media/9cd331bb9953578ef46d02075323eb42/href</a></iframe><p>We will not find a render object being created here. Instead, the element implements BuildContext which contains the findRenderObject method. This method leads us to the next getter:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3001d1870db8c0b3c8361dcff599f638/href">https://medium.com/media/3001d1870db8c0b3c8361dcff599f638/href</a></iframe><p>In the base case, elements may not create a render object, it is something that RenderObjectElement and its descendants do. However, the element must have a child containing a render object at some level of nesting.</p><p>It would appear too complicated, having to deal with three trees and different sets of responsibilities. But this is precisely what Flutter’s performance is built upon. Widgets are immutable configurations, therefore they are often being rebuilt. At the same time, they are pretty lightweight, so it does not affect performance. As for heavy elements, Flutter tries reusing them as much as possible.</p><p>Consider this example.</p><p><em>The text is displayed in the center of the screen. The code will look like this:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30de042b7bd960888dae7a98ca34e889/href">https://medium.com/media/30de042b7bd960888dae7a98ca34e889/href</a></iframe><p>The widget tree will have the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/0*DqGF9UsydAxjInsw" /></figure><p>Once Flutter has built all three trees, this is what we will get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/0*12kak8DZVfiYyTB1" /></figure><p>What happens if we change the text that we want to display?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/0*vl6TArImV6GZai7m" /></figure><p>Now we have a new widget tree. We mentioned that Flutter tries to make the most of the existing elements. Let us take a look at another method in the Widget class with a telling name <em>canUpdate</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/add09d0c589fcbc6a649c51990b06d8f/href">https://medium.com/media/add09d0c589fcbc6a649c51990b06d8f/href</a></iframe><p>We check the type and key of the previous widget and compare them with those of the new widget. If they are identical, there is no need to change the element.</p><p>Before the update, Center was the first element, and it remains there after the update. None of them have keys, it is a complete match. We can update the element’s association with the new widget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/0*hFcdOC0gERP39h-D" /></figure><p>Apart from having type and key, a widget is a description and a configuration. This means that parameter values needed for displaying might have changed. That is why the element must initiate updates of the render object after updating the association with the widget. Nothing changes for Center here. Let us continue examining the widgets.</p><p>Again, type and key suggest that there is no point in rebuilding the element. The text is a descendant of StatelessWidget and it does not have a direct display object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/0*bUVnI9EPBwwM-274" /></figure><p>Let us move on to RichText. As in the previous case, the widget has not changed its type, the keys are identical. The element updates the association with the new widget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/0*mhyJcn_jzuO-g1mg" /></figure><p>Now it is time to update properties. This will result in RenderParagraph displaying the new text value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/0*9lg9siSO4opL44qo" /></figure><p>We will see the expected result after the next painting frame.</p><p>That is how Flutter achieves such high performance.</p><p>This example illustrates a case where the widget structure remains unchanged. What happens if it does change? Flutter will try to make the most of already existing objects, as we know from the lifecycle description. At the same time, Flutter will create new elements for all new widgets whereas old ones that are no longer needed will be removed at the end of the frame.</p><p>To prove this point, let us consider this example in which we will be using the Flutter Inspector tool in Android Studio.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac21a5be5aad04974c44f73e93fb4c3a/href">https://medium.com/media/ac21a5be5aad04974c44f73e93fb4c3a/href</a></iframe><p>If we press the button, one of the widgets will change. Let us see what the inspector shows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*-SeE477j5ASfrcgf" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/0*LiL9tR_G3O2yG4O7" /></figure><p>As we can see, Flutter only rebuilt RenderPadding and reused the rest.</p><p>Here is another example, in which we will change the levels of nesting, thus changing the structure drastically.</p><p><em>Widget second() =&gt; Container(child: first(),);</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*5-5S5DFDlOJBjBmR" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/0*h89S7pp0fp0Ujt5-" /></figure><p>Although the tree appears to be the same, the elements and render objects have been rebuilt. This happened because Flutter compares by level. It does not matter that the tree remained mostly unchanged. This part was filtered out when Container and Row were being compared. However, this can be avoided If we use GlobalKey. Let us add this key to Row.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1129c004a94db0ca08e420a453b317d1/href">https://medium.com/media/1129c004a94db0ca08e420a453b317d1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/0*hfM6IkA5A-yX_nlR" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/0*_nF4b--0Zow_Vg3i" /></figure><p>When we told Flutter that this part can be reused, the framework was happy to oblige.</p><h3>In conclusion</h3><p>In this article we began to unveil the secrets of Flutter’s magic and found out that it is not only about widgets.</p><p>Flutter is a well-thought-out, coherent mechanism with its unique hierarchy and sets of responsibilities that allows you to build both esthetically pleasing and performant apps. We have only analyzed a small portion of Flutter, and we will continue exploring various aspects of its inner workings in future articles.</p><p>I hope that this article helped you learn more about how Flutter works and inspired you to seek for elegant and performant solutions during development.</p><h4>References</h4><p><em>Flutter Code<br>«How Flutter renders Widgets» Andrew Fitz Gibbon, Matt Sullivan</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=401503d2979e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>