<?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 Vasily Styagov on Medium]]></title>
        <description><![CDATA[Stories by Vasily Styagov on Medium]]></description>
        <link>https://medium.com/@VasyaFromRussia?source=rss-f1bbdcf4c59c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*m198HU-4d3W4KAk4lDElvQ.jpeg</url>
            <title>Stories by Vasily Styagov on Medium</title>
            <link>https://medium.com/@VasyaFromRussia?source=rss-f1bbdcf4c59c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:24:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@VasyaFromRussia/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[Shaders in Flutter]]></title>
            <link>https://medium.com/dev-artel/shaders-in-flutter-1562fd33b994?source=rss-f1bbdcf4c59c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1562fd33b994</guid>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Vasily Styagov]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 14:06:29 GMT</pubDate>
            <atom:updated>2023-10-20T14:06:29.957Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-UNfBgU1hCG8R_h4x7nrw.png" /></figure><h3>What is a shader?</h3><p>A shader is a computer program embedded into a rendering pipeline. It is a brief program that runs on the GPU and can be effectively parallelized. When executed, the shader can define the color of each pixel in a rendered image or transform the coordinates of a vertex.</p><h3>Why consider using them?</h3><p>Ever wondered how to incorporate eye-catching visual effects in your app or game? Like:</p><ul><li>Particle systems (for instance, smoke);</li><li>Ocean waves;</li><li>Ambient occlusion;</li><li>Global illumination.</li></ul><p>Utilize the full potential of your GPU by employing shaders for these purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*cZv-8dQT-4FQCKYkBKxzKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*mSMChXFev9uhcUMZEQGQbw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*i2PAE76UKwjI_njsIBtuhA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90gm3c4NTSxtLc62O5YkOA.jpeg" /><figcaption>Clockwise, starting from top left: particle systems, per-pixel lighting, global illumination, ambient occlusion.</figcaption></figure><h3>Types of shaders</h3><p>Let’s begin with basic definitions. A <strong>primitive</strong> refers to a group of vertices and the methods of linking them.</p><p>Shaders can be:</p><ul><li><strong>Fragment/pixel shaders</strong> are programs that execute during the rasterization stage. They operate on each pixel to determine its final color and can be used for tasks such as applying textures or calculating lighting. There are two fundamental concepts:<br>‣ <strong>Fragment.</strong> A renderer creates fragments, which are the smallest unit of data produced by rasterization. A fragment does not always correspond to a physical pixel. In cases of multi-sampling, several fragments combine to produce the color of a single pixel. The area of a fragment is related to the area of a pixel.<br>‣ <strong>Pixel</strong> is a singular point on the physical screen.</li><li><strong>Vertex shader</strong> takes only a single primitive as an argument and returns only a single primitive as a result.</li><li><strong>Geometry shaders</strong> take one primitive as input and can output zero or more primitives.</li><li><strong>Compute shaders</strong> are a type of shader that does not deal with graphics and instead utilizes GPU computational power for tasks such as physics computations.</li></ul><p>Let’s explain our rendering process in simple words. Imagine a scene made up of basic primitives.</p><ol><li>The user’s program defines primitives, colors, textures, camera position, and orientation through method calls of graphics APIs such as <a href="https://en.wikipedia.org/wiki/Direct3D">Direct3D</a> and <a href="https://en.wikipedia.org/wiki/Vulkan">Vulkan</a>.</li><li>Vertex shaders are supplied with primitive vertex data to undergo additional transformations, such as animations.</li><li>The geometry shader receives primitives with transformed vertices and has the option to either generate new primitives or output zero.</li><li>After applying viewport and perspective transformations as well as textures, the geometry generated by the geometry shader is rasterized to obtain the colors of pixels.</li><li>Fragment shaders alter the colors of pixels to simulate lighting and other per-pixel effects.</li></ol><h3>Simple example</h3><p>In its simplest form, a shader consists of the following parts:</p><ol><li><strong>Includes.</strong> The part describes dependencies of the shader. In this example, we include flutter/runtime_effect.glsl containing a convenient function to obtain coordinates of a fragment being processed.</li><li><strong>Uniforms.</strong> These are the parameters sent from a client to a shader program. They are called uniforms because their values remain constant across multiple calls to the program.</li><li><strong>Output fragment values.</strong> It’s the result of program execution. It can be a color or a depth value.</li><li><strong>The code of the program itself.</strong> The entry function (called main) contains code in a C-like language called GLSL.</li></ol><p>Here’s a simple example of a fragment shader:</p><pre>// 1<br>#include &lt;flutter/runtime_effect.glsl&gt;<br><br>// 2<br>uniform vec2 uSize;<br>uniform vec4 uColor;<br><br>// 3<br>out vec4 fragColor;<br><br>// 4<br>void main() {<br>    vec2 currentPos = FlutterFragCoord().xy / uSize;<br>    float multiplier = currentPos.x * currentPos.y;<br>    fragColor = vec4(uColor.r * multiplier, uColor.g * multiplier, uColor.b * multiplier, uColor.a);<br>}</pre><p>Let’s review it section by section:</p><ol><li>Section 1 includes handy helpers as we mentioned above.</li><li>Section 2 describes input data represented as vectors. The size vector contains 2 values denoting the X and Y coordinates, while the color vector consists of 4 values representing the red, green, blue, and alpha components.</li><li>In section 3, fragColor is a reserved word. The shader uses it to write a calculated color of the current fragment.</li><li>In the main function (section 4), we calculate the position within the range of [0..1]. Then we multiply it by each component of the color provided in the uniform. We create a new vec4 out of these values and set it as the output value.</li></ol><p>As a result we get a nice gradient from black to uColor. And this program is evaluated for every fragment of the rendered image.</p><h3>How to load a shader in Flutter code</h3><p>So, we devised a shader program. The following step is to use it within the application.</p><p>To access the program, it must be included in the project. The shader program file should be placed in the shaders directory located at the root of your project. To include the file in the project binary, reference it in the flutter/shaders section of the Pubspec.yaml file:</p><pre>flutter:<br>  shaders:<br>    - shaders/shader.frag</pre><p>Next we load the fragment program from assets:</p><pre>class ShaderWidget extends StatefulWidget {<br>  const ShaderWidget({Key? key}) : super(key: key);<br><br>  @override<br>  State&lt;ShaderWidget&gt; createState() =&gt; _ShaderWidgetState();<br>}<br><br>class _ShaderWidgetState extends State&lt;ShaderWidget&gt; {<br>  FragmentShader? shader;<br><br>  @override<br>  void initState() {<br>    super.initState();<br><br>    _loadMyShader();<br>  }<br><br>  Future&lt;void&gt; _loadMyShader() async {<br>    var program = await FragmentProgram.fromAsset(&#39;shaders/shader.frag&#39;);<br>    setState(() {<br>      shader = program.fragmentShader();<br>    });<br>  }<br><br>  // ... <br>}</pre><p>That’s it! Once the shader is loaded, we can paint it on Canvas:</p><pre>class MyPainter extends CustomPainter {<br>  MyPainter({<br>    required this.shader,<br>  });<br><br>  final FragmentShader shader;<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final random = Random();<br><br>    shader<br>      ..setFloat(0, size.width) // width<br>      ..setFloat(1, size.height) // height<br>      ..setFloat(2, random.nextDouble()) // red<br>      ..setFloat(3, random.nextDouble()) // green<br>      ..setFloat(4, random.nextDouble()) // blue<br>      ..setFloat(5, 1); // alpha<br><br>    final paint = Paint()..shader = shader;<br>    canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint);<br>  }<br><br>  @override<br>  bool shouldRepaint(covariant CustomPainter oldDelegate) =&gt; true;<br>}</pre><p>In the paint method, we pass uniform values to the shader. For instance, at the first position in the shader program, we have uniform vec2 uSize, which is a vector of two values. This implies that we should pass values to parameters with indices 0 and 1. These values are stored between frames and can be updated anytime.</p><p>Lastly, use this Painter.</p><pre>class _ShaderWidgetState extends State&lt;ShaderWidget&gt; {<br>  FragmentShader? shader;<br><br>  // ...<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final shader = this.shader;<br>    return shader == null // As the shader is loaded ascynchronously, we need to render something meanwhile<br>        ? const Center(<br>            child: CircularProgressIndicator(),<br>          )<br>        : CustomPaint(<br>            painter: MyPainter(shader: shader),<br>          );<br>  }<br>}</pre><p>Et voilá! We’ve just successfully painted a gradient with a fragment shader!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ERz9krFwiOGisAE23bQ9w.png" /></figure><h3>Flutter limitations</h3><p>When working with shaders in Flutter, it’s important to be aware of certain limitations and constraints that can impact your shader development.</p><ul><li>Only fragment shaders are supported.</li><li>Supported GLSL versions are 100–460.</li><li>Buffer Objects are not supported. Buffer Objects are essential for efficient data storage and transfer in OpenGL, and their absence in Flutter can impact certain advanced rendering techniques. Be prepared to work within this constraint when designing your shader-based applications.</li><li>Only 2D samples (textures) are supported. If your application relies on 3D textures or other types, you may need to find alternative solutions or work within the confines of 2D textures.</li><li>Unsigned types are not supported as well.</li></ul><p>Understanding these limitations is crucial for effectively using shaders in Flutter. By being mindful of these constraints and working within them, you can harness the power of shaders to enhance the visual quality and interactivity of your Flutter applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1562fd33b994" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-artel/shaders-in-flutter-1562fd33b994">Shaders in Flutter</a> was originally published in <a href="https://medium.com/dev-artel">Dev Artel</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to make Android Gesture Navigation respect your UI in Flutter]]></title>
            <link>https://medium.com/@VasyaFromRussia/how-to-make-android-gesture-navigation-respect-your-ui-in-flutter-255a17f610e6?source=rss-f1bbdcf4c59c------2</link>
            <guid isPermaLink="false">https://medium.com/p/255a17f610e6</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <dc:creator><![CDATA[Vasily Styagov]]></dc:creator>
            <pubDate>Sun, 10 May 2020 06:01:01 GMT</pubDate>
            <atom:updated>2020-05-11T12:01:28.325Z</atom:updated>
            <content:encoded><![CDATA[<p>Android 10 introduced Gesture Navigation which replaced those three boring buttons on the bottom of your screen. This navigation is convenient and simple for the user. But it may conflict with application UI. Gestures starting near the edges of the screen become interpreted as system navigation gestures. For example, when you have a video player with an edge-to-edge seek bar, dragging seek bar from the very edge of the screen can be interpreted as the “back” gesture. Your seek bar might also be on the bottom of the screen. In this case, any interaction will be regarded as switching between recent apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NN_FmYRcle4W3SJD.png" /></figure><p>Android SDK offers <a href="https://developer.android.com/reference/android/view/View#setSystemGestureExclusionRects(java.util.List%3Candroid.graphics.Rect%3E)">setSystemGestureExclusionRects</a> API to deal with this case. It sets rectangles on the screen in which the system shouldn’t intercept touch events.</p><p>And despite gesture navigation feels like a future, and Android 10 is almost a year in production, we still have this issue opened in Flutter repository: <a href="https://github.com/flutter/flutter/issues/54397">https://github.com/flutter/flutter/issues/54397</a> (as for May of 2020).</p><p>We cannot wait for exposure of this API, we need it right now. The only thing that we are offered is to use <a href="https://api.flutter.dev/flutter/widgets/MediaQueryData/systemGestureInsets.html">MediaQuery.systemGestureInset</a> to set paddings for conflicting UI elements, i.e. avoid conflict with system UI. It seems a poor solution to me.</p><p>But actually, Flutter already used this API. Take a look at this PR: <a href="https://github.com/flutter/engine/pull/11441">https://github.com/flutter/engine/pull/11441</a>.</p><p>Basically, it uses Platform channels to call this code in FlutterActivity:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69b0d4a644c140fca8cd574bf92e298d/href">https://medium.com/media/69b0d4a644c140fca8cd574bf92e298d/href</a></iframe><p>As now this code is reverted, we must implement the same by ourselves.</p><p>The first thing we need is platform channel. Let’s create a new Flutter app, add Slider to StatefulWidget and create a static instance of MethodChanel (a named for communicating with platform code) in its State.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c61ef9634bd4ea39a9730d7fcd909d9b/href">https://medium.com/media/c61ef9634bd4ea39a9730d7fcd909d9b/href</a></iframe><p>To execute platform code, we need to call platform.invokeMethod and pass the name of desired method as String and arguments as dynamic . Then we must handle it on the Android side: we need to override configureFlutterEngine in MainActivity and set up a handler for the corresponding method channel:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84bf533191e049eb0082faf183d9e97d/href">https://medium.com/media/84bf533191e049eb0082faf183d9e97d/href</a></iframe><p>This code contains unchecked cast, so treat it as you wish. Key moments here:</p><ol><li>We create MethodChannel with the same name as in Dart code.</li><li>We read method name as String and attributes as Object , so we need to cast it to the desired type. Be careful: Dart can only serialize primitive types, arrays of numbers, List and Map . In this case, the attributes object is List&lt;Map&lt;String, Int&gt;&gt; .</li><li>Then we parse rectangles which should be excluded from the system navigation and call setSystemGestureExclusionRect method itself. Note that the total height of rectangles must be less than 200dp. To reset the safe zones just call this method with an empty list. Remember that this handler is called on the main thread, so either avoid long computations or take care of threading.</li><li>Finally, we must report the result or error to Flutter with result attribute of the method call handler.</li></ol><p>It’s time to return to Flutter.</p><p>Let’s find the Slider bounding box and exclude it from system navigation. You might have noticed the sliderKey variable in _MyHomePageState . We’re going to use it to find this widget in the widget tree and get its size right after the widget tree is rendered using WidgetsBinding.addPostFrameCallback .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47a51a50002829de36aa1fc39d3cfdde/href">https://medium.com/media/47a51a50002829de36aa1fc39d3cfdde/href</a></iframe><p>After build method executed, we get RenderBox for the Slider and create a rectangle with its constraints adding threshold on top and bottom for better UX. Note that RenderBox works with Flutter’s logical pixels, but setSystemGestureExclusionRect requires physical pixels. So we must multiply all the values by ratio of the screen.</p><p>Now we can drag the slider edge to edge in the whole area it takes without being afraid to close the app with awkward movement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*D865WS27XEtWhSu56mL3rQ.gif" /></figure><p>I hope, the next stable release of Flutter will bring support for Android gesture navigation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=255a17f610e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Expanding text in Flutter]]></title>
            <link>https://medium.com/@VasyaFromRussia/expanding-text-in-flutter-92736226ace5?source=rss-f1bbdcf4c59c------2</link>
            <guid isPermaLink="false">https://medium.com/p/92736226ace5</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Vasily Styagov]]></dc:creator>
            <pubDate>Sat, 14 Mar 2020 12:17:15 GMT</pubDate>
            <atom:updated>2020-03-14T21:59:48.251Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m pretty sure that your app contains a lot of text: titles, descriptions, hints, etc. And not all of those texts are necessary for the user to see. So, sometimes, you want to hide part of them. A short description of a movie provides enough information for a user to decide if he wants to read more. And the common pattern is to truncate this text, maybe ellipsize it, to allow the user to expand it in some way (e.g. tapping on the whole text or on the ellipsis).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FA1FbAUbYqvoERYCOnwqzg.png" /></figure><p>If you want to crop the text and allow the user to expand it with a tap — there is a very simple solution. We just need to createStatefulWidget with a boolean property indicating that the text is expanded (e.g. isExpanded). Then we need to wrap the Text widget with GestureDetector and invert isExpanded property in its onTap callback. The overflow property of Text defines the way the text is cropped. Also, we define maxLines property depending on the current state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf7d31da7fe5533dadecc44fc0816dbc/href">https://medium.com/media/cf7d31da7fe5533dadecc44fc0816dbc/href</a></iframe><p>Ok, it was easy. Default implementation of Text offers only 4 options on overflow:</p><ol><li>TextOverflow.clip crops overflowing text;</li><li>TextOverflow.fade fades the end of the last line to transparent;</li><li>TextOverflow.ellipsis uses ellipsis to indicate that the text has overflowed;</li><li>TextOverflow.visible renders overflowing text outside of its container.</li></ol><p>But what if we need to customize the ellipsis?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*exxJVE0Vyy0mEjedfkZO2Q.jpeg" /></figure><h3>Here comes TextPainter</h3><p>TextPainter allows you to draw your text right on Canvas , and it provides you with this Canvas and Size in paint() method. Also, TextPainter has ellipsis property, that allows you to override the string which will be substituted at the end of the cropped text. TextPainter allows us to set ellipsis and define the maximum number of lines. But it needs CustomPaint to render. And CustomPaint works in pair with CustomPainter , so we need to wrap use the TextPainter inside of CustomPainter . Note that you also must set textDirection to let TextPainter know where the line’s end is.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6da467e63e995ce2032273ead044c4d6/href">https://medium.com/media/6da467e63e995ce2032273ead044c4d6/href</a></iframe><p>And voilà, there’s the custom ellipsis!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*Rsm5qLSWU1Pmql0DRa9N_Q.png" /></figure><p>But this solution is not very flexible: “more” is just the part of the text. Also, you could notice that CustomPaint requires the size of the area for painting. How to calculate it? We’ll find it out a bit later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ePflO3HHgIfZ2Gff8fI8Mw.jpeg" /></figure><h3>Some maths with lines</h3><p>But my goal was to implement an expandable text widget that ellipsizes the text based on the “maximum lines” attribute. It also must be expanded by a tap on the word “more” appended after the ellipsis. Also, I want this “more” word to be styled differently from the main text.</p><p>Different styles, tappable parts… Sounds like we need RichText . But it can ellipsize text just like the regular Text do (actually, Text renders RichText under the hood). So, if it had many spans in it, all of them would be cropped.</p><p>Ok, let’s get to it.</p><p>First of all, we need to know how the text is gonna be rendered. Unfortunately, I couldn’t figure out how text would render line by line, but we can get rectangles describing bounds of these lines. RenderObjectserves this purpose. It defines the base layout model. Hence we can get bounds of the text after layout. But we need Constraints to perform layout, so let’s wrap it in LayoutBuilder . Since text can either be expanded or stay the same, the widget must hold the state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25e2226b428379ba11e19cc841e6a759/href">https://medium.com/media/25e2226b428379ba11e19cc841e6a759/href</a></iframe><p>Now we can get the RenderParapgraph ( RenderObject that displays paragraph of text), layout it and get bounds of each line with getBoxesForSelection method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ad508f9a61e73096a862e5db0e2d162/href">https://medium.com/media/1ad508f9a61e73096a862e5db0e2d162/href</a></iframe><p>If the number of lines is less than the maximum number or if the widget is in the expanded state we can just render our text as-is.</p><p>Otherwise, let’s do some simple maths. We cannot get the content of each line. But we know the length of each line in pixels. So we can:</p><ol><li>Calculate the total length of the maximum number of lines;</li><li>Calculate the total length of all the lines;</li><li>Count the ratio of these values;</li><li>Take the approximate length of cropped string, by multiplying the length of the full string on this ratio;</li><li>Take substring of the length that we’ve got.</li></ol><p>Here’s the relevant code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/548606c0a23b84175c39d4916d7c96fd/href">https://medium.com/media/548606c0a23b84175c39d4916d7c96fd/href</a></iframe><p>All we need to do now is to create TextSpan with this new string and desired style and append ellipsis and “more” word with the other style. But the resulting string may be longer than needed, and in that case just layout it again and check the number of lines. If it’s greater than the desired maximum number of lines… Ok, let’s just crop the substring of length ellipsis + &quot;more&quot; from the end of the truncated string. That’s all. No more layouts. Now we can prepare the final RichText .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*kyfHasliPNuWqViyQevsfg.gif" /></figure><p>Not too accurate (I mean, the “More” word is not always at the very end of the last line), but you can be sure that a user will see the exact number of lines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92736226ace5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>