<?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 Valerii Novykov on Medium]]></title>
        <description><![CDATA[Stories by Valerii Novykov on Medium]]></description>
        <link>https://medium.com/@valerii.novykov?source=rss-41dbaf902a79------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wkvM7qhyycqPCc1wfzV_rQ.jpeg</url>
            <title>Stories by Valerii Novykov on Medium</title>
            <link>https://medium.com/@valerii.novykov?source=rss-41dbaf902a79------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:48:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@valerii.novykov/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 to Measure a Flutter Widget Before Rendering]]></title>
            <link>https://medium.com/@valerii.novykov/how-to-measure-a-flutter-widget-before-rendering-808048265cc8?source=rss-41dbaf902a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/808048265cc8</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <dc:creator><![CDATA[Valerii Novykov]]></dc:creator>
            <pubDate>Fri, 20 Jun 2025 07:12:34 GMT</pubDate>
            <atom:updated>2025-06-20T07:27:00.996Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hfZIMlED8soo6Kyqsc_HHg.png" /></figure><p>Flutter provides robust tools for dynamically handling UI layouts, but occasionally developers need to know the exact size of a widget before it renders. Tools like <strong>LayoutBuilder</strong> provide information about the constraints from the parent widget before rendering, but not the actual size of the child widget — only its constraints. In contrast, using <strong>GlobalKey</strong> and <strong>RenderBox</strong> lets you access the real size of a widget, but only after it has been rendered. But what if you need this information ahead of time?</p><p>In this article, we’ll explore a practical workaround leveraging Flutter’s internal rendering mechanisms — specifically using <strong>PipelineOwner</strong> and <strong>BuildOwner</strong> — to measure widgets before they hit the screen.</p><h4>Background: Understanding PipelineOwner and BuildOwner</h4><ul><li><strong>PipelineOwner</strong> manages the rendering pipeline in Flutter, overseeing layout, paint, and semantics phases. It schedules and processes layout and painting tasks.</li><li><strong>BuildOwner</strong> handles widget tree management and performs widget build tasks, managing widget state and updating the widget tree.</li></ul><p>Using these objects directly is an advanced practice, creating an off-screen rendering environment to measure widgets without visible rendering.</p><h4><strong>Why Measure Widgets Early?</strong></h4><p>Imagine you’re dynamically arranging a complex layout, adapting elements precisely, or handling advanced scenarios such as rendering conditional UI elements based on available space. Knowing widget dimensions beforehand can significantly simplify these tasks.</p><h4><strong>Solution Overview</strong></h4><p>We’ll create a utility class <strong>MeasureWidgetUtil</strong> to encapsulate the process of measuring widgets. This utility will:</p><ul><li>Create a temporary render tree.</li><li>Attach the widget to this tree.</li><li>Measure its layout based on provided constraints.</li><li>Return precise dimensions.</li></ul><h4><strong>Implementation Steps</strong></h4><p><strong>1. Create MeasureWidgetUtil Utility</strong></p><pre>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter/rendering.dart&#39;;<br><br>/// A utility class for measuring the size of a widget before it is rendered.<br>///<br>/// This class provides functionality to measure the size of a given widget with<br>/// specific constraints and text direction. This can be particularly useful<br>/// for scenarios such as positioning elements precisely in a layout,<br>/// or dynamically adjusting the UI based on widget sizes.<br>///<br>/// NOTE: Using this utility can be resource-intensive because it creates<br>/// a temporary render tree and performs a layout pass.<br>///<br>/// To optimize performance:<br>/// - Limit the frequency of measurements.<br>/// - Cache measurement results when possible.<br>/// - Avoid measuring complex widgets frequently.<br>class MeasureWidgetUtil {<br>  /// Measures the size of the given [widget] with the<br>  /// specified [constraints] and [textDirection].<br>  ///<br>  /// The [constraints] parameter specifies the box constraints that<br>  /// the widget should adhere to during measurement.<br>  /// It should be provided in cases where the widget being measured<br>  /// might have an unconstrained width or height.<br>  ///<br>  /// The [textDirection] parameter defines the text direction to<br>  /// use when measuring the widget.<br>  /// It is used when the widget being measured contains text in its<br>  /// subtree. Otherwise, it can be ignored.<br>  ///<br>  /// Returns the measured [Size] of the widget.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// Size widgetSize = MeasureWidgetUtil.measureWidget(SizedBox(width: 10, height: 20));<br>  /// print(widgetSize); // Size(10, 20)<br>  /// ```<br>  static Size measureWidget(Widget widget,<br>      {BoxConstraints constraints = const BoxConstraints(),<br>      TextDirection textDirection = TextDirection.ltr}) {<br>    final measureData = _createMeasureData(textDirection, constraints);<br><br>    final element = _attachWidgetToRenderTree(widget, measureData);<br><br>    return _getSize(element, measureData);<br>  }<br><br>  static _MeasureData _createMeasureData(<br>      TextDirection textDirection, BoxConstraints constraints) {<br>    final pipelineOwner = PipelineOwner();<br>    final rootView = pipelineOwner.rootNode = _MeasurementView(constraints);<br>    final buildOwner = BuildOwner(focusManager: FocusManager());<br><br>    return _MeasureData(<br>        textDirection: textDirection,<br>        pipelineOwner: pipelineOwner,<br>        buildOwner: buildOwner,<br>        rootView: rootView);<br>  }<br><br>  static RenderObjectToWidgetElement&lt;RenderBox&gt; _attachWidgetToRenderTree(<br>      Widget widget, _MeasureData data) {<br>    return RenderObjectToWidgetAdapter&lt;RenderBox&gt;(<br>      container: data.rootView,<br>      debugShortDescription: &#39;[root]&#39;,<br>      child: Directionality(<br>        textDirection: data.textDirection,<br>        child: widget,<br>      ),<br>    ).attachToRenderTree(data.buildOwner);<br>  }<br><br>  static Size _getSize(<br>      RenderObjectToWidgetElement&lt;RenderBox&gt; element, _MeasureData data) {<br>    try {<br>      data.rootView.scheduleInitialLayout();<br>      data.pipelineOwner.flushLayout();<br><br>      return data.rootView.size;<br>    } catch (e) {<br>      debugLog(&#39;[ERROR MEASURE WIDGET]: $e&#39;);<br>      return Size.zero;<br>    } finally {<br>      // Clean up.<br>      element.update(<br>          RenderObjectToWidgetAdapter&lt;RenderBox&gt;(container: data.rootView));<br>      data.buildOwner.finalizeTree();<br>    }<br>  }<br>}<br><br>class _MeasurementView extends RenderBox<br>    with RenderObjectWithChildMixin&lt;RenderBox&gt; {<br>  final BoxConstraints boxConstraints;<br><br>  _MeasurementView(this.boxConstraints);<br><br>  @override<br>  void performLayout() {<br>    assert(child != null);<br>    child!.layout(boxConstraints, parentUsesSize: true);<br>    size = child!.size;<br>  }<br><br>  @override<br>  void debugAssertDoesMeetConstraints() =&gt; true;<br>}<br><br>class _MeasureData {<br>  final TextDirection textDirection;<br>  final PipelineOwner pipelineOwner;<br>  final BuildOwner buildOwner;<br>  final _MeasurementView rootView;<br><br>  const _MeasureData(<br>      {required this.textDirection,<br>      required this.pipelineOwner,<br>      required this.buildOwner,<br>      required this.rootView});<br>}<br><br>void debugLog(Object? message) {<br>  if (!kDebugMode) return;<br><br>  debugPrint(message.toString());<br>}</pre><p><strong>2 . Use the Utility</strong></p><pre>final size = MeasureWidgetUtil.measureWidget(<br>    SizedBox(width: 50, height: 30),<br>  );<br>print(&#39;Widget Size: $size&#39;); // Output: Widget Size: Size(50.0, 30.0)</pre><h4><strong>Conclusion</strong></h4><p>The utility we’ve created offers a practical workaround to measure widget dimensions prior to rendering. While useful, it remains a workaround, best used for simpler widgets and less frequent calculations. Always aim to cache measurement results when feasible to maintain optimal performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=808048265cc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Custom Dashed and Dotted Dividers in Flutter]]></title>
            <link>https://medium.com/@valerii.novykov/how-to-create-custom-dashed-and-dotted-dividers-in-flutter-a3cbe637fb86?source=rss-41dbaf902a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3cbe637fb86</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Valerii Novykov]]></dc:creator>
            <pubDate>Thu, 19 Jun 2025 07:22:06 GMT</pubDate>
            <atom:updated>2025-06-19T07:22:06.246Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-f9E5vk5goqMZT2jqNANQ.png" /></figure><p>Dividers are essential UI elements for separating content clearly in mobile apps. While Flutter provides solid dividers out-of-the-box, developers often face scenarios where dashed or dotted dividers better suit their design needs. This article will guide you through creating customizable dashed and dotted dividers (<strong>DashedDivider</strong>, <strong>DottedDivider</strong>, <strong>DashedVerticalDivider</strong>, <strong>DottedVerticalDivider</strong>) that seamlessly integrate with Flutter’s theming system.</p><h4><strong>Background: Why Custom Dividers?</strong></h4><p>Flutter’s default divider widgets (<strong>Divider</strong> and <strong>VerticalDivider</strong>) only support solid lines. In many design systems, dashed or dotted lines provide subtle visual distinctions, enhancing readability and aesthetics.</p><p>Using these custom dividers allows developers to:</p><ul><li>Enhance UI consistency.</li><li>Follow design system guidelines precisely.</li><li>Improve visual differentiation without clutter.</li></ul><h4><strong>Problem Scenario</strong></h4><p>Imagine designing an application with distinct sections separated by solid lines. Your UI designer requests dotted or dashed separators to enhance visual appeal. However, Flutter’s default widgets don’t support this directly, leading you to create repetitive, custom solutions.</p><h4><strong>Solution Overview</strong></h4><p>We’ll implement four custom widgets:</p><ol><li><strong>DashedDivider</strong></li><li><strong>DashedVerticalDivider</strong></li><li><strong>DottedDivider</strong></li><li><strong>DottedVerticalDivider</strong></li></ol><p>These widgets will:</p><ul><li>Integrate seamlessly with Flutter’s theme (DividerThemeData).</li><li>Provide configurable parameters similar to default dividers.</li><li>Ensure consistency across the app.</li></ul><h4><strong>Implementation Steps</strong></h4><p><strong>1. DividerThemeProvider Class</strong></p><p>We first create a helper class, DividerThemeProvider, to manage defaults and theming consistently.</p><pre>class DividerThemeProvider {<br>  final DividerThemeData _dividerTheme;<br>  final ThemeData _theme;<br>  final DividerThemeData _defaults;<br><br>  double? _width;<br>  double? _height;<br>  double? _thickness;<br>  double? _indent;<br>  double? _endIndent;<br>  Color? _color;<br><br>  DividerThemeProvider._(BuildContext context)<br>      : _dividerTheme = DividerTheme.of(context),<br>        _theme = Theme.of(context),<br>        _defaults = Theme.of(context).useMaterial3<br>            ? _DividerDefaultsM3(context)<br>            : _DividerDefaultsM2(context);<br><br>  static DividerThemeProvider of(BuildContext context) {<br>    return DividerThemeProvider._(context);<br>  }<br><br>  DividerThemeProvider withDefaults({<br>    double? width,<br>    double? height,<br>    double? thickness,<br>    double? indent,<br>    double? endIndent,<br>    Color? color,<br>  }) {<br>    _width = width ?? _width;<br>    _height = height ?? _height;<br>    _thickness = thickness ?? _thickness;<br>    _indent = indent ?? _indent;<br>    _endIndent = endIndent ?? _endIndent;<br>    _color = color ?? _color;<br><br>    return this;<br>  }<br><br>  double get width =&gt; _width ?? _dividerTheme.space ?? _defaults.space!;<br><br>  double get height =&gt; _height ?? _dividerTheme.space ?? _defaults.space!;<br><br>  double get thickness =&gt;<br>      _thickness ?? _dividerTheme.thickness ?? _defaults.thickness!;<br><br>  double get indent =&gt; _indent ?? _dividerTheme.indent ?? _defaults.indent!;<br><br>  double get endIndent =&gt;<br>      _endIndent ?? _dividerTheme.endIndent ?? _defaults.endIndent!;<br><br>  Color get color =&gt;<br>      _color ?? _dividerTheme.color ?? _defaults.color ?? _theme.dividerColor;<br>}<br><br>class _DividerDefaultsM3 extends DividerThemeData {<br>  const _DividerDefaultsM3(this.context)<br>      : super(<br>          space: 16,<br>          thickness: 1.0,<br>          indent: 0,<br>          endIndent: 0,<br>        );<br><br>  final BuildContext context;<br><br>  @override<br>  Color? get color =&gt; Theme.of(context).colorScheme.outlineVariant;<br>}<br><br>class _DividerDefaultsM2 extends DividerThemeData {<br>  const _DividerDefaultsM2(this.context)<br>      : super(<br>          space: 16,<br>          thickness: 0,<br>          indent: 0,<br>          endIndent: 0,<br>        );<br><br>  final BuildContext context;<br><br>  @override<br>  Color? get color =&gt; Theme.of(context).dividerColor;<br>}</pre><p><strong>2 . Custom Painters</strong></p><p>Next, we create two custom painters:</p><ul><li>DottedLinePainter: for rendering dotted lines.</li></ul><pre>class DottedLinePainter extends CustomPainter {<br>  final Color color;<br>  final double dotRadius;<br>  final double dotSpace;<br>  final bool isVertical;<br>  final double mainAxisOffset;<br><br>  DottedLinePainter({<br>    required this.color,<br>    required this.dotRadius,<br>    required this.dotSpace,<br>    this.isVertical = false,<br>    this.mainAxisOffset = 0.0,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final paint = Paint()<br>      ..color = color<br>      ..style = PaintingStyle.fill;<br><br>    final effRadius = dotRadius &lt;= 0 ? 0.5 : dotRadius;<br>    final mainAxisSize = _getMainAxisSize(size);<br>    final crossAxisPosition = _getCrossAxisPosition(size);<br><br>    canvas.clipRect(Rect.fromLTWH(0, 0, size.width, size.height));<br><br>    double currentPosition = effRadius + mainAxisOffset;<br><br>    while ((currentPosition - effRadius) &lt; mainAxisSize) {<br>      final circleCenter =<br>          _calculateCircleCenter(crossAxisPosition, currentPosition);<br><br>      canvas.drawCircle(<br>        circleCenter,<br>        effRadius,<br>        paint,<br>      );<br><br>      currentPosition += (effRadius * 2) + dotSpace;<br>    }<br>  }<br><br>  double _getMainAxisSize(Size size) {<br>    return isVertical ? size.height : size.width;<br>  }<br><br>  double _getCrossAxisPosition(Size size) {<br>    return isVertical ? size.width / 2 : size.height / 2;<br>  }<br><br>  Offset _calculateCircleCenter(<br>      double crossAxisPosition, double currentPosition) {<br>    return isVertical<br>        ? Offset(crossAxisPosition, currentPosition)<br>        : Offset(currentPosition, crossAxisPosition);<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) =&gt; false;<br>}</pre><ul><li>DashedLinePainter: for rendering dashed lines.</li></ul><pre>class DashedLinePainter extends CustomPainter {<br>  final Color color;<br>  final double thickness;<br>  final double dashLength;<br>  final double dashSpace;<br>  final bool isVertical;<br>  final double mainAxisOffset;<br><br>  DashedLinePainter({<br>    required this.color,<br>    required this.thickness,<br>    required this.dashLength,<br>    required this.dashSpace,<br>    this.isVertical = false,<br>    this.mainAxisOffset = 0.0,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final paint = Paint()<br>      ..color = color<br>      ..strokeWidth = thickness &lt;= 0 ? 1 : thickness;<br><br>    final mainAxisSize = _getMainAxisSize(size);<br>    final crossAxisPosition = _getCrossAxisPosition(size);<br><br>    canvas.clipRect(Rect.fromLTWH(0, 0, size.width, size.height));<br><br>    double currentPosition = mainAxisOffset;<br><br>    while (currentPosition &lt; mainAxisSize) {<br>      double nextDashEnd = currentPosition + dashLength;<br><br>      if (nextDashEnd &gt; mainAxisSize) {<br>        nextDashEnd = mainAxisSize;<br>      }<br><br>      final start = _calculateStartOffset(crossAxisPosition, currentPosition);<br>      final end = _calculateEndOffset(crossAxisPosition, nextDashEnd);<br><br>      canvas.drawLine(start, end, paint);<br><br>      currentPosition += dashLength + dashSpace;<br>    }<br>  }<br><br>  double _getMainAxisSize(Size size) {<br>    return isVertical ? size.height : size.width;<br>  }<br><br>  double _getCrossAxisPosition(Size size) {<br>    return isVertical ? size.width / 2 : size.height / 2;<br>  }<br><br>  Offset _calculateStartOffset(<br>      double crossAxisPosition, double currentPosition) {<br>    return isVertical<br>        ? Offset(crossAxisPosition, currentPosition)<br>        : Offset(currentPosition, crossAxisPosition);<br>  }<br><br>  Offset _calculateEndOffset(double crossAxisPosition, double nextDashEnd) {<br>    return isVertical<br>        ? Offset(crossAxisPosition, nextDashEnd)<br>        : Offset(nextDashEnd, crossAxisPosition);<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) =&gt; false;<br>}</pre><p>These painters handle drawing lines with customizable thickness, spacing, and colors.</p><p><strong>3. Divider Widgets</strong></p><p>Finally, we implement the divider widgets using our painters:</p><ul><li><strong>Dashed Divider</strong></li></ul><pre>class DashedDivider extends StatelessWidget {<br>  /// The divider&#39;s height extent.<br>  ///<br>  /// The divider itself is always drawn as a horizontal line that is centered<br>  /// within the height specified by this value.<br>  ///<br>  /// If this is null, then the [DividerThemeData.space] is used. If that is<br>  /// also null, then this defaults to 16.0.<br>  final double? height;<br><br>  /// The thickness of the line drawn within the divider.<br>  ///<br>  /// A divider with a [thickness] of 0.0 is always drawn as a line with a<br>  /// height of exactly one device pixel.<br>  ///<br>  /// If this is null, then the [DividerThemeData.thickness] is used. If<br>  /// that is also null, then this defaults to 0.0.<br>  final double? thickness;<br><br>  /// The amount of empty space to the leading edge of the divider.<br>  ///<br>  /// If this is null, then the [DividerThemeData.indent] is used. If that is<br>  /// also null, then this defaults to 0.0.<br>  final double? indent;<br><br>  /// The amount of empty space to the trailing edge of the divider.<br>  ///<br>  /// If this is null, then the [DividerThemeData.endIndent] is used. If that is<br>  /// also null, then this defaults to 0.0.<br>  final double? endIndent;<br><br>  /// The color to use when painting the line.<br>  ///<br>  /// If this is null, then the [DividerThemeData.color] is used. If that is<br>  /// also null, then [ThemeData.dividerColor] is used.<br>  final Color? color;<br><br>  /// The length of each dash in the dashed line.<br>  final double dashLength;<br><br>  /// The space between each dash in the dashed line.<br>  final double dashSpace;<br><br>  /// The offset along the main axis for the starting position of the dashes.<br>  ///<br>  /// This value determines how far from the start the first dash will be drawn,<br>  /// allowing for fine-tuning the positioning of the dashed line. A positive value<br>  /// shifts the dashes forward, while a negative value moves them backward along<br>  /// the main axis.<br>  ///<br>  /// The default value is 0.0, meaning the dashes start at the beginning of the line.<br>  final double mainAxisOffset;<br><br>  const DashedDivider({<br>    super.key,<br>    this.height,<br>    this.thickness,<br>    this.color,<br>    this.indent,<br>    this.endIndent,<br>    this.dashLength = 5,<br>    this.dashSpace = 5,<br>    this.mainAxisOffset = 0.0,<br>  })  : assert(height == null || height &gt;= 0.0),<br>        assert(thickness == null || thickness &gt;= 0.0),<br>        assert(indent == null || indent &gt;= 0.0),<br>        assert(endIndent == null || endIndent &gt;= 0.0);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final theme = DividerThemeProvider.of(context).withDefaults(<br>      height: height,<br>      thickness: thickness,<br>      indent: indent,<br>      endIndent: endIndent,<br>      color: color,<br>    );<br><br>    return Container(<br>      margin: EdgeInsets.only(left: theme.indent, right: theme.endIndent),<br>      height: theme.height,<br>      width: double.infinity,<br>      child: CustomPaint(<br>        painter: DashedLinePainter(<br>          color: theme.color,<br>          thickness: theme.thickness,<br>          dashLength: dashLength,<br>          dashSpace: dashSpace,<br>          mainAxisOffset: mainAxisOffset,<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><ul><li><strong>Dashed Vertical Divider</strong></li></ul><pre>class DashedVerticalDivider extends StatelessWidget {<br>  /// The divider&#39;s width.<br>  ///<br>  /// The divider itself is always drawn as a vertical line that is centered<br>  /// within the width specified by this value.<br>  ///<br>  /// If this is null, then the [DividerThemeData.space] is used. If that is<br>  /// also null, then this defaults to 16.0.<br>  final double? width;<br><br>  /// The thickness of the line drawn within the divider.<br>  ///<br>  /// A divider with a [thickness] of 0.0 is always drawn as a line with a<br>  /// width of exactly one device pixel.<br>  ///<br>  /// If this is null, then the [DividerThemeData.thickness] is used. If<br>  /// that is also null, then this defaults to 0.0.<br>  final double? thickness;<br><br>  /// The amount of empty space on top of the divider.<br>  ///<br>  /// If this is null, then the [DividerThemeData.indent] is used. If that is<br>  /// also null, then this defaults to 0.0.<br>  final double? indent;<br><br>  /// The amount of empty space under the divider.<br>  ///<br>  /// If this is null, then the [DividerThemeData.endIndent] is used. If that is<br>  /// also null, then this defaults to 0.0.<br>  final double? endIndent;<br><br>  /// The color to use when painting the line.<br>  ///<br>  /// If this is null, then the [DividerThemeData.color] is used. If that is<br>  /// also null, then [ThemeData.dividerColor] is used.<br>  final Color? color;<br><br>  /// The length of each dash in the dashed line.<br>  final double dashLength;<br><br>  /// The space between each dash in the dashed line.<br>  final double dashSpace;<br><br>  /// The offset along the main axis for the starting position of the dashes.<br>  ///<br>  /// This value determines how far from the start the first dash will be drawn,<br>  /// allowing for fine-tuning the positioning of the dashed line. A positive value<br>  /// shifts the dashes forward, while a negative value moves them backward along<br>  /// the main axis.<br>  ///<br>  /// The default value is 0.0, meaning the dashes start at the beginning of the line.<br>  final double mainAxisOffset;<br><br>  const DashedVerticalDivider({<br>    super.key,<br>    this.width,<br>    this.thickness,<br>    this.color,<br>    this.indent,<br>    this.endIndent,<br>    this.dashLength = 5,<br>    this.dashSpace = 5,<br>    this.mainAxisOffset = 0.0,<br>  })  : assert(width == null || width &gt;= 0.0),<br>        assert(thickness == null || thickness &gt;= 0.0),<br>        assert(indent == null || indent &gt;= 0.0),<br>        assert(endIndent == null || endIndent &gt;= 0.0);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final theme = DividerThemeProvider.of(context).withDefaults(<br>      width: width,<br>      thickness: thickness,<br>      indent: indent,<br>      endIndent: endIndent,<br>      color: color,<br>    );<br><br>    return Container(<br>      margin: EdgeInsets.only(top: theme.indent, bottom: theme.endIndent),<br>      width: theme.width,<br>      height: double.infinity,<br>      child: CustomPaint(<br>        painter: DashedLinePainter(<br>          color: theme.color,<br>          thickness: theme.thickness,<br>          dashLength: dashLength,<br>          dashSpace: dashSpace,<br>          isVertical: true,<br>          mainAxisOffset: mainAxisOffset,<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><ul><li><strong>Dotted Divider</strong></li></ul><pre>class DottedDivider extends StatelessWidget {<br>  /// The divider&#39;s height extent.<br>  ///<br>  /// The divider itself is always drawn as a horizontal line that is centered<br>  /// within the height specified by this value.<br>  ///<br>  /// If this is null, then the [DividerThemeData.space] is used. If that is<br>  /// also null, then this defaults to 16.0.<br>  final double? height;<br><br>  /// The thickness of the dots drawn within the divider.<br>  ///<br>  /// A divider with a [thickness] of 0.0 is always drawn as a line with a<br>  /// height of exactly one device pixel.<br>  ///<br>  /// If this is null, then the [DividerThemeData.thickness] is used. If<br>  /// that is also null, then this defaults to 0.0.<br>  final double? thickness;<br><br>  /// The amount of empty space to the leading edge of the divider.<br>  ///<br>  /// If this is null, then the [DividerThemeData.indent] is used. If that is<br>  /// also null, then this defaults to 0.0.<br>  final double? indent;<br><br>  /// The amount of empty space to the trailing edge of the divider.<br>  ///<br>  /// If this is null, then the [DividerThemeData.endIndent] is used. If that is<br>  /// also null, then this defaults to 0.0.<br>  final double? endIndent;<br><br>  /// The color to use when painting the dots.<br>  ///<br>  /// If this is null, then the [DividerThemeData.color] is used. If that is<br>  /// also null, then [ThemeData.dividerColor] is used.<br>  final Color? color;<br><br>  /// The space between each dot in the dotted line.<br>  final double dotSpace;<br><br>  /// The offset along the main axis for the starting position of the dots.<br>  ///<br>  /// This value determines how far from the start the first dot will be drawn,<br>  /// allowing for fine-tuning the positioning of the dotted line. A positive value<br>  /// shifts the dots forward, while a negative value moves them backward along<br>  /// the main axis.<br>  ///<br>  /// The default value is 0.0, meaning the dots start at the beginning of the line.<br>  final double mainAxisOffset;<br><br>  const DottedDivider({<br>    super.key,<br>    this.height,<br>    this.thickness,<br>    this.color,<br>    this.indent,<br>    this.endIndent,<br>    this.dotSpace = 3.0,<br>    this.mainAxisOffset = 0.0,<br>  })  : assert(height == null || height &gt;= 0.0),<br>        assert(thickness == null || thickness &gt;= 0.0),<br>        assert(indent == null || indent &gt;= 0.0),<br>        assert(endIndent == null || endIndent &gt;= 0.0);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final theme = DividerThemeProvider.of(context).withDefaults(<br>      height: height,<br>      thickness: thickness,<br>      indent: indent,<br>      endIndent: endIndent,<br>      color: color,<br>    );<br><br>    final dotRadius = theme.thickness / 2;<br><br>    return Container(<br>      margin: EdgeInsets.only(left: theme.indent, right: theme.endIndent),<br>      height: theme.height,<br>      width: double.infinity,<br>      child: CustomPaint(<br>        painter: DottedLinePainter(<br>          color: theme.color,<br>          dotRadius: dotRadius,<br>          dotSpace: dotSpace,<br>          mainAxisOffset: mainAxisOffset,<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><ul><li><strong>Dotted Vertical Divider</strong></li></ul><pre>class DottedVerticalDivider extends StatelessWidget {<br>  /// The divider&#39;s width.<br>  ///<br>  /// The divider itself is always drawn as a vertical line that is centered<br>  /// within the width specified by this value.<br>  ///<br>  /// If this is null, then the [DividerThemeData.space] is used. If that is<br>  /// also null, then this defaults to 16.0.<br>  final double? width;<br><br>  /// The thickness of the line drawn within the divider.<br>  ///<br>  /// A divider with a [thickness] of 0.0 is always drawn as a line with a<br>  /// width of exactly one device pixel.<br>  ///<br>  /// If this is null, then the [DividerThemeData.thickness] is used. If<br>  /// that is also null, then this defaults to 0.0.<br>  final double? thickness;<br><br>  /// The amount of empty space on top of the divider.<br>  ///<br>  /// If this is null, then the [DividerThemeData.indent] is used. If that is<br>  /// also null, then this defaults to 0.0.<br>  final double? indent;<br><br>  /// The amount of empty space under the divider.<br>  ///<br>  /// If this is null, then the [DividerThemeData.endIndent] is used. If that is<br>  /// also null, then this defaults to 0.0.<br>  final double? endIndent;<br><br>  /// The color to use when painting the line.<br>  ///<br>  /// If this is null, then the [DividerThemeData.color] is used. If that is<br>  /// also null, then [ThemeData.dividerColor] is used.<br>  final Color? color;<br><br>  /// The space between each dot in the dotted line.<br>  final double dotSpace;<br><br>  /// The offset along the main axis for the starting position of the dots.<br>  ///<br>  /// This value determines how far from the start the first dot will be drawn,<br>  /// allowing for fine-tuning the positioning of the dotted line. A positive value<br>  /// shifts the dots forward, while a negative value moves them backward along<br>  /// the main axis.<br>  ///<br>  /// The default value is 0.0, meaning the dots start at the beginning of the line.<br>  final double mainAxisOffset;<br><br>  const DottedVerticalDivider({<br>    super.key,<br>    this.width,<br>    this.thickness,<br>    this.color,<br>    this.indent,<br>    this.endIndent,<br>    this.dotSpace = 3.0,<br>    this.mainAxisOffset = 0.0,<br>  })  : assert(width == null || width &gt;= 0.0),<br>        assert(thickness == null || thickness &gt;= 0.0),<br>        assert(indent == null || indent &gt;= 0.0),<br>        assert(endIndent == null || endIndent &gt;= 0.0);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final theme = DividerThemeProvider.of(context).withDefaults(<br>      width: width,<br>      thickness: thickness,<br>      indent: indent,<br>      endIndent: endIndent,<br>      color: color,<br>    );<br><br>    final dotRadius = theme.thickness / 2;<br><br>    return Container(<br>      margin: EdgeInsets.only(top: theme.indent, bottom: theme.endIndent),<br>      width: theme.width,<br>      height: double.infinity,<br>      child: CustomPaint(<br>        painter: DottedLinePainter(<br>          color: theme.color,<br>          dotRadius: dotRadius,<br>          dotSpace: dotSpace,<br>          isVertical: true,<br>          mainAxisOffset: mainAxisOffset,<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h4><strong>Code Example</strong></h4><p>Here’s how you can use created widgets:</p><pre>SizedBox(<br>              height: 100,<br>              child: Row(<br>                spacing: 20,<br>                children: [<br>                  Flexible(<br>                    flex: 4,<br>                    child: Column(<br>                      spacing: 20,<br>                      mainAxisAlignment: MainAxisAlignment.center,<br>                      children: [<br>                        // Using DottedDivider<br>                        DashedDivider(<br>                          color: Colors.red,<br>                          thickness: 4,<br>                          dashLength: 7,<br>                          dashSpace: 4,<br>                        ),<br>                        // Using DashedDivider<br>                        DottedDivider(<br>                          color: Colors.orange,<br>                          thickness: 5,<br>                          dotSpace: 5,<br>                        ),<br>                      ],<br>                    ),<br>                  ),<br>                  Flexible(<br>                    child: Row(<br>                      spacing: 20,<br>                      mainAxisAlignment: MainAxisAlignment.center,<br>                      children: [<br>                        // Using DottedVerticalDivider<br>                        DottedVerticalDivider(<br>                          color: Colors.blue,<br>                          thickness: 5,<br>                          dotSpace: 5,<br>                        ),<br>                        // Using DashedVerticalDivider<br>                        DashedVerticalDivider(<br>                          color: Colors.green,<br>                          thickness: 4,<br>                          dashLength: 7,<br>                          dashSpace: 4,<br>                        ),<br>                      ],<br>                    ),<br>                  ),<br>                ],<br>              ),<br>            )</pre><p>As a result we get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*jPm38A6Jnx62sAfSrLmr3Q.png" /></figure><h4><strong>Conclusion</strong></h4><p>Custom dashed and dotted dividers significantly enhance your app’s design flexibility, providing clear content separation while maintaining visual consistency. Integrating these widgets with Flutter’s theming makes your UI both elegant and maintainable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3cbe637fb86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Enhance Date Handling in Dart with Custom Extensions]]></title>
            <link>https://medium.com/@valerii.novykov/how-to-enhance-date-handling-in-dart-with-custom-extensions-cfd7d73ce98e?source=rss-41dbaf902a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfd7d73ce98e</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-tips]]></category>
            <dc:creator><![CDATA[Valerii Novykov]]></dc:creator>
            <pubDate>Wed, 18 Jun 2025 06:40:13 GMT</pubDate>
            <atom:updated>2025-06-18T06:40:13.221Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u8BfBGhsfwuKtp13fYMnvg.png" /></figure><p>Working with dates and times in Dart can often involve repetitive and boilerplate code, especially when performing common tasks like calculating the first or last day of a month, checking if a date is today, or adjusting date components. Wouldn’t it be great if these frequent operations were simplified? In this article, you’ll learn how to create powerful and easy-to-use Dart extensions to improve your date handling code.</p><h4><strong>Background</strong></h4><p>When developing Flutter or Dart applications, it’s common to manipulate or compare dates frequently. These operations might seem straightforward initially but can quickly lead to repetitive code, cluttering your codebase and making it harder to maintain.</p><h4><strong>Problem Scenario</strong></h4><p>Consider the following typical date operations:</p><pre>final date = DateTime(2024, 5, 15);<br><br>// Finding first and last day of the month<br>final firstDayOfMonth = DateTime(date.year, date.month, 1);<br>final lastDayOfMonth = DateTime(date.year, date.month + 1, 0);<br><br>// Checking if date is today<br>final bool isToday = DateTime.now().year == date.year &amp;&amp;<br>    DateTime.now().month == date.month &amp;&amp;<br>    DateTime.now().day == date.day;</pre><p>These tasks are repetitive and verbose, making your code less readable and maintainable.</p><h4><strong>Solution Overview</strong></h4><p>The solution is to create two concise Dart extensions: <strong>DateTimeInfo</strong> and <strong>DateTimeManipulator</strong>. These extensions encapsulate commonly used date operations, significantly simplifying your code.</p><h4><strong>Implementation Steps</strong></h4><p><strong>1 . Create DateTimeInfo Extension</strong></p><p>This extension provides getters and methods for common checks and operations on dates.</p><pre>extension DateTimeInfo on DateTime {<br>  /// The first day of the month.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final date = DateTime(2024, 5, 15);<br>  /// print(date.firstDayOfMonth); // 2024-05-01 00:00:00.000<br>  /// ```<br>  DateTime get firstDayOfMonth =&gt; DateTime(year, month, 1);<br><br>  /// The last day of the month.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final date = DateTime(2024, 5, 15);<br>  /// print(date.lastDayOfMonth); // 2024-05-31 00:00:00.000<br>  /// ```<br>  DateTime get lastDayOfMonth =&gt; DateTime(year, month + 1, 0);<br><br>  /// A new [DateTime] object with the time part set to zero.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final date = DateTime(2024, 5, 21, 7, 30);<br>  /// print(date.withoutTimePart); // 2024-05-21 00:00:00.000<br>  /// ```<br>  DateTime get withoutTimePart =&gt; DateTime(year, month, day);<br><br>  /// Whether the current date is in the current month.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// print(DateTime.now().isCurrentMonth); // true<br>  /// ```<br>  bool get isCurrentMonth {<br>    DateTime now = _currentDate();<br>    return year == now.year &amp;&amp; month == now.month;<br>  }<br><br>  /// Whether the current date is today.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// print(DateTime.now().isToday); // true<br>  /// ```<br>  bool get isToday {<br>    DateTime now = _currentDate();<br>    return isSameDay(now);<br>  }<br><br>  /// Whether the current date is yesterday.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// print(DateTime.now().subtractDays(1).isYesterday); // true<br>  /// ```<br>  bool get isYesterday {<br>    DateTime yesterday = _currentDate().subtract(const Duration(days: 1));<br>    return isSameDay(yesterday);<br>  }<br><br>  DateTime _currentDate() {<br>    return DateTime.now().withoutTimePart;<br>  }<br><br>  /// Whether the current date is in the past.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// print(DateTime.now().subtractDays(1).isInPast); // true<br>  /// ```<br>  bool get isInPast =&gt;<br>      _withoutMilliseconds.isBefore(DateTime.now()._withoutMilliseconds);<br><br>  /// Whether the current date is in the future.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// print(DateTime.now().addDays(1).isInFuture); // true<br>  /// ```<br>  bool get isInFuture =&gt;<br>      _withoutMilliseconds.isAfter(DateTime.now()._withoutMilliseconds);<br><br>  DateTime get _withoutMilliseconds =&gt;<br>      DateTime(year, month, day, hour, minute, second);<br><br>  /// Whether the current date is within the range (startDate, endDate).<br>  ///<br>  /// The [includeEndDate] parameter specifies whether to include the end date in the range.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final startDate = DateTime(2024, 5, 1);<br>  /// final endDate = DateTime(2024, 5, 31);<br>  /// final currentDate = DateTime(2024, 5, 15);<br>  /// print(currentDate.isDayInRange(startDate, endDate)); // true<br>  /// ```<br>  bool isDayInRange(DateTime startDate, DateTime endDate,<br>      {bool includeEndDate = false}) {<br>    final start = startDate.withoutTimePart;<br>    final end =<br>        endDate.withoutTimePart.add(Duration(days: includeEndDate ? 1 : 0));<br><br>    return isSameDay(start) || (isAfter(start) &amp;&amp; isBefore(end));<br>  }<br><br>  /// The difference in months between the current date and [other].<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final currentDate = DateTime.now();<br>  /// final prevDate = currentDate.subtractMonths(2);<br>  /// print(currentDate.differenceInMonths(prevDate)); // 2<br>  /// ```<br>  int differenceInMonths(DateTime other) {<br>    int yearDifference = year - other.year;<br>    int monthDifference = month - other.month;<br>    return (yearDifference * 12 + monthDifference).abs();<br>  }<br><br>  /// The difference in days between the current date and [other].<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final currentDate = DateTime.now();<br>  /// final prevDate = currentDate.subtractDays(2);<br>  /// print(currentDate.differenceInDays(prevDate)); // 2<br>  /// ```<br>  int differenceInDays(DateTime other) {<br>    Duration duration = difference(other);<br>    return duration.inDays.abs();<br>  }<br><br>  /// The difference in minutes between the current date and [other].<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final currentDate = DateTime.now();<br>  /// final prevDate = currentDate.subtractMinutes(2);<br>  /// print(currentDate.differenceInMinutes(prevDate)); // 2<br>  /// ```<br>  int differenceInMinutes(DateTime other) {<br>    Duration duration = difference(other);<br>    return duration.inMinutes.abs();<br>  }<br><br>  /// Whether the current date is in the same year as [other].<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final firstDate = DateTime(2024, 5, 1);<br>  /// final secondDate = DateTime(2024, 5, 31);<br>  /// print(firstDate.isSameYear(secondDate)); // true<br>  /// ```<br>  bool isSameYear(DateTime other) {<br>    return year == other.year;<br>  }<br><br>  /// Whether the current date is in the same month and year as [other].<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final firstDate = DateTime(2024, 5, 1);<br>  /// final secondDate = DateTime(2024, 5, 31);<br>  /// print(firstDate.isSameMonth(secondDate)); // true<br>  /// ```<br>  bool isSameMonth(DateTime other) {<br>    return year == other.year &amp;&amp; month == other.month;<br>  }<br><br>  /// Whether the current date is in the same week as [other].<br>  ///<br>  /// The week is considered to start on Monday and end on Sunday.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final firstDate = DateTime(2024, 5, 20);<br>  /// final secondDate = DateTime(2024, 5, 21);<br>  /// print(firstDate.isSameWeek(secondDate)); // true<br>  /// ```<br>  bool isSameWeek(DateTime other) {<br>    DateTime thisMonday = withoutTimePart.subtract(Duration(days: weekday - 1));<br>    DateTime otherMonday =<br>        other.withoutTimePart.subtract(Duration(days: other.weekday - 1));<br>    return thisMonday.isSameDay(otherMonday);<br>  }<br><br>  /// Whether the current date is the same day as [other].<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// print(DateTime.now().isSameDay(DateTime.now())); // true<br>  /// ```<br>  bool isSameDay(DateTime other) {<br>    return year == other.year &amp;&amp; month == other.month &amp;&amp; day == other.day;<br>  }<br><br>  /// Whether the current date is before or at the same moment as [other].<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final firstDate = DateTime(2024, 5, 20);<br>  /// final secondDate = DateTime(2024, 5, 21);<br>  /// print(firstDate.isBeforeOrAtSameMomentAs(secondDate)); // true<br>  /// ```<br>  bool isBeforeOrAtSameMomentAs(DateTime other) =&gt;<br>      isBefore(other) || isAtSameMomentAs(other);<br><br>  /// Whether the current date is after or at the same moment as [other].<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final firstDate = DateTime(2024, 5, 20);<br>  /// final secondDate = DateTime(2024, 5, 21);<br>  /// print(secondDate.isAfterOrAtSameMomentAs(firstDate)); // true<br>  /// ```<br>  bool isAfterOrAtSameMomentAs(DateTime other) =&gt;<br>      isAfter(other) || isAtSameMomentAs(other);<br>}</pre><p><strong>2 . Create DateTimeManipulator Extension</strong></p><p>This extension allows easy manipulation of date values.</p><pre>extension DateTimeManipulator on DateTime {<br>  /// Sets the hour of the current date, keeping the day, month,<br>  /// and year unchanged.<br>  ///<br>  /// The [hour] parameter is the hour to set.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final date = DateTime(2024, 5, 15);<br>  /// print(date.setHours(10)); // 2024-05-15 10:00:00.000<br>  /// ```<br>  DateTime setHours(int hour) =&gt; DateTime(year, month, day, hour);<br><br>  /// Sets the hour and minutes of the current date, keeping the day,<br>  /// month, and year unchanged.<br>  ///<br>  /// The [hour] parameter is the hour to set.<br>  /// The [minutes] parameter is the minutes to set.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final date = DateTime(2024, 5, 15);<br>  /// print(date.setHoursAndMinutes(10, 30)); // 2024-05-15 10:30:00.000<br>  /// ```<br>  DateTime setHoursAndMinutes(int hour, int minutes) {<br>    return DateTime(year, month, day, hour, minutes);<br>  }<br><br>  /// Adds the specified number of months to the current date.<br>  ///<br>  /// The [months] parameter is the number of months to add.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final date = DateTime(2024, 5, 15);<br>  /// print(date.addMonths(2)); // 2024-07-15 00:00:00.000<br>  /// ```<br>  DateTime addMonths(int months) =&gt; _adjustMonths(months);<br><br>  /// Subtracts the specified number of months from the current date.<br>  ///<br>  /// The [months] parameter is the number of months to subtract.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final date = DateTime(2024, 5, 15);<br>  /// print(date.subtractMonths(2)); // 2024-03-15 00:00:00.000<br>  /// ```<br>  DateTime subtractMonths(int months) =&gt; _adjustMonths(-months);<br><br>  /// Adjusts the current date by the specified number of months.<br>  ///<br>  /// The [months] parameter is the number of months to adjust.<br>  /// This method handles the addition and subtraction of months,<br>  /// adjusting the year and day as necessary.<br>  DateTime _adjustMonths(int months) {<br>    int totalMonths = (year * 12 + month) + months;<br>    int newYear = totalMonths ~/ 12;<br>    int newMonth = totalMonths % 12;<br><br>    if (newMonth == 0) {<br>      newYear -= 1;<br>      newMonth = 12;<br>    }<br><br>    int newDay = day;<br>    int daysInNewMonth = DateTime(newYear, newMonth + 1, 0).day;<br><br>    if (newDay &gt; daysInNewMonth) {<br>      newDay = daysInNewMonth;<br>    }<br><br>    return DateTime(newYear, newMonth, newDay, hour, minute, second,<br>        millisecond, microsecond);<br>  }<br><br>  /// Adds the specified number of days to the current date.<br>  ///<br>  /// The [days] parameter is the number of days to add.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final date = DateTime(2024, 5, 15);<br>  /// print(date.addDays(10)); // 2024-05-25 00:00:00.000<br>  /// ```<br>  DateTime addDays(int days) =&gt; add(Duration(days: days));<br><br>  /// Subtracts the specified number of days from the current date.<br>  ///<br>  /// The [days] parameter is the number of days to subtract.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final date = DateTime(2024, 5, 15);<br>  /// print(date.subtractDays(10)); // 2024-05-05 00:00:00.000<br>  /// ```<br>  DateTime subtractDays(int days) =&gt; subtract(Duration(days: days));<br><br>  /// Adds the specified number of hours to the current date.<br>  ///<br>  /// The [hours] parameter is the number of hours to add.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final date = DateTime(2024, 5, 15);<br>  /// print(date.addHours(5)); // 2024-05-15 05:00:00.000<br>  /// ```<br>  DateTime addHours(int hours) =&gt; add(Duration(hours: hours));<br><br>  /// Subtracts the specified number of hours from the current date.<br>  ///<br>  /// The [hours] parameter is the number of hours to subtract.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final date = DateTime(2024, 5, 15, 10);<br>  /// print(date.subtractHours(5)); // 2024-05-15 05:00:00.000<br>  /// ```<br>  DateTime subtractHours(int hours) =&gt; subtract(Duration(hours: hours));<br><br>  /// Adds the specified number of minutes to the current date.<br>  ///<br>  /// The [minutes] parameter is the number of minutes to add.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final date = DateTime(2024, 5, 15, 10, 0);<br>  /// print(date.addMinutes(30)); // 2024-05-15 10:30:00.000<br>  /// ```<br>  DateTime addMinutes(int minutes) =&gt; add(Duration(minutes: minutes));<br><br>  /// Subtracts the specified number of minutes from the current date.<br>  ///<br>  /// The [minutes] parameter is the number of minutes to subtract.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// final date = DateTime(2024, 5, 15, 10, 30);<br>  /// print(date.subtractMinutes(30)); // 2024-05-15 10:00:00.000<br>  /// ```<br>  DateTime subtractMinutes(int minutes) =&gt; subtract(Duration(minutes: minutes));<br>}</pre><h4><strong>Usage Example</strong></h4><p>Now your previous cumbersome operations are simplified:</p><pre>final date = DateTime(2024, 5, 15);<br><br>final firstDayOfMonth = date.firstDayOfMonth; // 2024-05-01<br>final lastDayOfMonth = date.lastDayOfMonth; // 2024-05-31<br>final bool isToday = date.isToday; // false</pre><h4><strong>Conclusion</strong></h4><p>Using these custom Dart extensions, your date-handling code becomes cleaner, more concise, and easier to manage. Implementing these patterns helps reduce code redundancy and enhances readability, ultimately improving your overall coding productivity and experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfd7d73ce98e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Custom Text Input Formatters in Flutter]]></title>
            <link>https://medium.com/@valerii.novykov/how-to-create-custom-text-input-formatters-in-flutter-1dc9fb7741e9?source=rss-41dbaf902a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dc9fb7741e9</guid>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Valerii Novykov]]></dc:creator>
            <pubDate>Tue, 17 Jun 2025 09:20:00 GMT</pubDate>
            <atom:updated>2025-06-17T09:20:00.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3FFFwUkFt5WLEW4TRwLjQ.png" /></figure><p>In Flutter applications, ensuring users input data correctly is crucial. Imagine you’re building a promotional code input field: the code must contain exactly six uppercase letters or digits. Simply restricting keyboard types isn’t enough because special characters can still be entered. To enhance user experience, automatically formatting input can help avoid user errors. This article demonstrates how to achieve this effectively using custom <strong>TextInputFormatter</strong> implementations.</p><h4><strong>Background (What/Why)</strong></h4><p><strong>TextInputFormatter</strong> is a powerful Flutter utility allowing developers to enforce text input constraints dynamically. Whether restricting input to letters, numbers, controlling text length, or automatically converting text case, custom formatters streamline the data entry process.</p><h4><strong>Problem Scenario</strong></h4><p>Consider an application that accepts promotional codes — always exactly 6 characters, comprising uppercase letters and digits. Users mistakenly input lowercase letters or special characters, causing validation failures. To improve user experience, we need automatic correction or prevention of invalid entries.</p><h4><strong>Solution Overview</strong></h4><p>We’ll create a flexible custom formatters to handle:</p><ul><li>Letter, digit, or combined alphanumeric restrictions.</li><li>Upper or lowercase conversion.</li><li>Length constraints.</li></ul><h4><strong>Implementation Steps</strong></h4><p><strong>1. Define Enum Constraints</strong></p><pre>/// Specifies the text case conversion to be applied to a string.<br>enum TextCase {<br>  /// Preserve the original text case.<br>  original,<br><br>  /// Convert all characters to upper case.<br>  upperCase,<br><br>  /// Convert all characters to lower case.<br>  lowerCase,<br>}<br><br>/// Specifies the format constraints to be applied to a string.<br>/// These constraints define patterns that the input text should conform to.<br>enum FormatConstraints {<br>  /// Allow only alphabetic characters (a-z, A-Z).<br>  onlyAlphabetic(r&#39;[^a-zA-Z]&#39;),<br><br>  /// Allow only numeric characters (0-9).<br>  onlyNumeric(r&#39;[^0-9]&#39;),<br><br>  /// Allow only alphanumeric characters (a-z, A-Z, 0-9).<br>  onlyAlphanumeric(r&#39;[^a-zA-Z0-9]&#39;),<br><br>  /// No constraints, allow any characters.<br>  none(r&#39;[\s\S]*&#39;);<br><br>  final String _pattern;<br><br>  /// Returns the pattern as a [RegExp] object.<br>  Pattern get pattern =&gt; RegExp(_pattern);<br><br>  const FormatConstraints(this._pattern);<br>}</pre><p><strong>2. Implement Base Formatter</strong></p><p>This base class handles common text transformations:</p><pre>class _ReplaceAllFormatter extends TextInputFormatter {<br>  final Pattern _from;<br>  final String _to;<br>  final TextCase _textCase;<br>  final int? _maxLength;<br><br>  const _ReplaceAllFormatter(<br>    this._from,<br>    this._to, {<br>    TextCase textCase = TextCase.original,<br>    int? maxLength,<br>  }) : _textCase = textCase,<br>       _maxLength = maxLength;<br><br>  @override<br>  TextEditingValue formatEditUpdate(<br>    TextEditingValue oldValue,<br>    TextEditingValue newValue,<br>  ) {<br>    String newText = _adjustText(newValue);<br><br>    int newOffset = _adjustOffset(oldValue, newValue, newText);<br><br>    return newValue.copyWith(<br>      text: newText,<br>      selection: TextSelection.collapsed(offset: newOffset),<br>      composing: TextRange.empty,<br>    );<br>  }<br><br>  String _adjustText(TextEditingValue newValue) {<br>    String newText = newValue.text.replaceAll(_from, _to);<br><br>    if (_textCase != TextCase.original) {<br>      newText = _textCase == TextCase.upperCase<br>          ? newText.toUpperCase()<br>          : newText.toLowerCase();<br>    }<br><br>    return _maxLength == null || _maxLength! &gt; newText.length<br>        ? newText<br>        : newText.substring(0, _maxLength);<br>  }<br><br>  int _adjustOffset(<br>    TextEditingValue oldValue,<br>    TextEditingValue newValue,<br>    String newText,<br>  ) {<br>    int newOffset = newValue.selection.end;<br><br>    if (newOffset &lt; 1 &amp;&amp; newText.length &gt; oldValue.text.length) {<br>      newOffset += 1;<br>    } else if (newOffset &gt;= 1 &amp;&amp; newValue.text.length &gt; newText.length) {<br>      newOffset -= 1;<br>    }<br><br>    return newOffset.clamp(0, newText.length);<br>  }<br>}</pre><p><strong>3. Create Specific Formatters</strong></p><p>AlphabeticFormatter:</p><pre>/// A formatter that allows only alphabetic characters.<br>/// It can optionally convert text to a specific case and limit the text length.<br>class AlphabeticFormatter extends _ReplaceAllFormatter {<br>  /// Creates an [AlphabeticFormatter].<br>  ///<br>  /// The [textCase] parameter specifies the case conversion to be<br>  /// applied (e.g., original, upper case, or lower case).<br>  /// The [maxLength] parameter specifies the maximum length of the input text.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// TextField(<br>  ///   inputFormatters: [<br>  ///     AlphabeticFormatter(textCase: TextCase.upperCase, maxLength: 6),<br>  ///   ],<br>  /// )<br>  /// ```<br>  AlphabeticFormatter({TextCase textCase = TextCase.original, int? maxLength})<br>    : super(<br>        FormatConstraints.onlyAlphabetic.pattern,<br>        &#39;&#39;,<br>        textCase: textCase,<br>        maxLength: maxLength,<br>      );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*oPhkLKKuTJk7U0n30J6whA.gif" /></figure><p>NumericFormatter:</p><pre>/// A formatter that allows only numeric characters.<br>/// It can optionally limit the text length.<br>class NumericFormatter extends _ReplaceAllFormatter {<br>  /// Creates a [NumericFormatter].<br>  ///<br>  /// The [maxLength] parameter specifies the maximum length of the input text.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// TextField(<br>  ///   inputFormatters: [<br>  ///     NumericFormatter(maxLength: 6),<br>  ///   ],<br>  /// )<br>  /// ```<br>  NumericFormatter({int? maxLength})<br>    : super(FormatConstraints.onlyNumeric.pattern, &#39;&#39;, maxLength: maxLength);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*e9PCR_4UAjfleyoVR8d2cA.gif" /></figure><p>AlphanumericFormatter:</p><pre>/// A formatter that allows only alphanumeric characters.<br>/// It can optionally convert text to a specific case and limit the text length.<br>class AlphanumericFormatter extends _ReplaceAllFormatter {<br>  /// Creates an [AlphanumericFormatter].<br>  ///<br>  /// The [textCase] parameter specifies the case conversion to be<br>  /// applied (e.g., original, upper case, or lower case).<br>  /// The [maxLength] parameter specifies the maximum length of the input text.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// TextField(<br>  ///   inputFormatters: [<br>  ///     AlphanumericFormatter(textCase: TextCase.upperCase, maxLength: 6),<br>  ///   ],<br>  /// )<br>  /// ```<br>  AlphanumericFormatter({TextCase textCase = TextCase.original, int? maxLength})<br>    : super(<br>        FormatConstraints.onlyAlphanumeric.pattern,<br>        &#39;&#39;,<br>        textCase: textCase,<br>        maxLength: maxLength,<br>      );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*HUBvwaHaHEaqQ_Tg8PUfgQ.gif" /></figure><h4><strong>Conclusion</strong></h4><p>Implementing custom TextInputFormatter classes provides robust and flexible input handling, significantly enhancing user experience. It ensures compliance with input requirements and reduces validation errors. Consider applying similar techniques to improve data entry accuracy in your Flutter apps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dc9fb7741e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Resolve Gesture Conflicts in Flutter with Scroll and Pinch-to-Zoom]]></title>
            <link>https://medium.com/@valerii.novykov/how-to-resolve-gesture-conflicts-in-flutter-with-scroll-and-pinch-to-zoom-6d6b2f525550?source=rss-41dbaf902a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d6b2f525550</guid>
            <category><![CDATA[flutter-tutorial]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <dc:creator><![CDATA[Valerii Novykov]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 08:14:57 GMT</pubDate>
            <atom:updated>2025-06-16T08:14:57.950Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZN3aD-t5kjV9HW9TC6vWw.png" /></figure><p>If you’ve ever struggled with pinch-to-zoom gestures conflicting with horizontal or vertical scrolling in Flutter apps, this article is for you. Learn a simple, effective way to handle gesture conflicts and deliver a smooth user experience.</p><h4><strong>Introduction</strong></h4><p>In my previous <a href="https://medium.com/@valerii.novykov/how-to-create-a-resettable-pinch-to-zoom-widget-in-flutter-20542246e9b9">article</a>, we explored creating a widget (<strong>ResettableInteractiveViewer</strong>) that resets zoom state after pinch gestures. However, combining pinch-to-zoom functionality with horizontal scrolling widgets, like <strong>PageView</strong>, introduces gesture conflicts. This article guides you through solving this specific conflict scenario.</p><h4><strong>Background: Why Does Gesture Conflict Occur?</strong></h4><p>Gesture conflicts arise when Flutter’s gesture recognizers compete for input. For example, a horizontal scroll (PageView) gesture interferes with pinch-to-zoom gestures, causing unexpected behavior such as accidental page changes while zooming.</p><h4><strong>Problem Scenario</strong></h4><p>Imagine building an image gallery using PageView, enabling users to pinch-to-zoom images. A straightforward implementation might look like:</p><pre>ResettableInteractiveViewer(<br>          child: PageView(<br>            children: [<br>              Image.network(<br>                &#39;https://picsum.photos/720/1080/?random=1&#39;,<br>                fit: BoxFit.cover,<br>              ),<br>              Image.network(<br>                &#39;https://picsum.photos/720/1080/?random=2&#39;,<br>                fit: BoxFit.cover,<br>              ),<br>            ],<br>          ),<br>        )</pre><p>Here, a pinch-to-zoom gesture can mistakenly trigger horizontal scrolling, disrupting user interaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*uG6VbyRwvs9FDVVJ-jr-_Q.gif" /></figure><h4><strong>Solution Overview</strong></h4><p>To address this, disable horizontal scrolling (<strong>PageView</strong>) when multiple touch pointers (fingers) are detected, indicative of a pinch gesture. We’ll use a custom widget called <strong>PointersListener</strong> to detect this scenario.</p><h4><strong>Implementation Steps</strong></h4><p><strong>1. Create the PointersListener Widget</strong></p><pre>class PointersListener extends StatefulWidget {<br>  /// A builder function that provides the current [BuildContext] and a boolean<br>  /// indicating whether more than one pointer (touch) is currently active.<br>  ///<br>  /// This function should return the widget subtree that depends on the number<br>  /// of active pointers. It is called every time the number of pointers changes<br>  /// from one to many or vice versa.<br>  ///<br>  /// The [moreThanOnePointer] parameter is `true` when two or more pointers<br>  /// are detected on the screen simultaneously, otherwise `false`.<br>  final Function(BuildContext context, bool moreThanOnePointer) builder;<br><br>  const PointersListener({super.key, required this.builder});<br><br>  @override<br>  State&lt;PointersListener&gt; createState() =&gt; _PointersListenerState();<br>}<br><br>class _PointersListenerState extends State&lt;PointersListener&gt; {<br>  final Set&lt;int&gt; _touchIndexes = {};<br><br>  bool get _moreThanOnePointer =&gt; _touchIndexes.length &gt; 1;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Listener(<br>      onPointerDown: (event) {<br>        _savePointerIndex(event.pointer);<br>      },<br>      onPointerMove: (event) {<br>        _savePointerIndex(event.pointer);<br>      },<br>      onPointerCancel: (event) {<br>        _clearPointerIndex(event.pointer);<br>      },<br>      onPointerUp: (event) {<br>        _clearPointerIndex(event.pointer);<br>      },<br>      child: widget.builder(context, _moreThanOnePointer),<br>    );<br>  }<br><br>  void _savePointerIndex(int index) {<br>    _actionHandler(() =&gt; _touchIndexes.add(index));<br>  }<br><br>  void _clearPointerIndex(int index) {<br>    _actionHandler(() =&gt; _touchIndexes.remove(index));<br>  }<br><br>  void _actionHandler(VoidCallback action) {<br>    final prev = _moreThanOnePointer;<br><br>    action();<br><br>    final next = _moreThanOnePointer;<br><br>    if (prev != next) {<br>      setState(() {});<br>    }<br>  }<br>}</pre><p><strong>2. Apply Conditional Scroll Physics</strong></p><pre>PointersListener(<br>          builder: (_, moreThanOnePointer) =&gt; ResettableInteractiveViewer(<br>            child: PageView(<br>              physics: moreThanOnePointer // Disable scrolling when more than one pointer is active<br>                  ? const NeverScrollableScrollPhysics()<br>                  : const BouncingScrollPhysics(),<br>              children: [<br>                Image.network(<br>                  &#39;https://picsum.photos/720/1080/?random=1&#39;,<br>                  fit: BoxFit.cover,<br>                ),<br>                Image.network(<br>                  &#39;https://picsum.photos/720/1080/?random=2&#39;,<br>                  fit: BoxFit.cover,<br>                ),<br>              ],<br>            ),<br>          ),<br>        )</pre><p>As a result we get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*q0QvMfbGKpVmX5H9SkIOgQ.gif" /></figure><h4><strong>Conclusion</strong></h4><p>By detecting multiple pointer gestures with <strong>PointersListener</strong> and conditionally adjusting scroll behavior, you resolve gesture conflicts effectively. This enhances user experience by providing intuitive and error-free interaction. Consider further extending this pattern for other gesture-based widgets.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d6b2f525550" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a Resettable Pinch-to-Zoom Widget in Flutter]]></title>
            <link>https://medium.com/@valerii.novykov/how-to-create-a-resettable-pinch-to-zoom-widget-in-flutter-20542246e9b9?source=rss-41dbaf902a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/20542246e9b9</guid>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Valerii Novykov]]></dc:creator>
            <pubDate>Fri, 13 Jun 2025 11:31:29 GMT</pubDate>
            <atom:updated>2025-06-13T11:36:54.034Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qXTF-4Y8O9czRIfHJNKVWw.png" /></figure><p>Zooming into content is a fundamental interaction users expect, especially when viewing detailed images or documents. However, sometimes you might want the zoom state to reset automatically after the user finishes interacting. Imagine inspecting a product image — zooming in for details is great, but you might prefer it returns to its original size once you’re done. This article explains how to create a custom widget in Flutter that supports pinch-to-zoom and automatically resets after the gesture ends.</p><h4><strong>Background (What/Why)</strong></h4><p>Flutter provides an <strong>InteractiveViewer</strong> widget that supports pinch-to-zoom and pan gestures out-of-the-box. However, it doesn’t automatically reset to its original scale after interaction. Implementing this feature improves user experience by ensuring the UI stays tidy and predictable after detailed viewing.</p><h4><strong>Problem Scenario</strong></h4><p>Consider an e-commerce app where users often zoom into product images. Without an automatic reset, images could remain overly zoomed or misaligned, confusing the user.</p><h4><strong>Solution Overview</strong></h4><p>We’ll create a <strong>ResettableInteractiveViewer</strong>, a simple custom widget wrapping Flutter’s built-in <strong>InteractiveViewer</strong>. It handles gestures, allows pinch-to-zoom, and returns to its original state upon gesture completion.</p><h4><strong>Implementation Steps</strong></h4><p><strong>1. Create ResettableInteractiveViewer widget:</strong></p><pre>class ResettableInteractiveViewer extends StatefulWidget {<br>  /// [Widget] to be displayed and interacted with.<br>  final Widget child;<br><br>  /// Whether zooming and panning are enabled. Defaults to true.<br>  final bool zoomEnabled;<br><br>  /// Callback that is invoked when a zoom interaction starts.<br>  final VoidCallback? onZoomStart;<br><br>  /// Callback that is invoked when a zoom interaction ends.<br>  final VoidCallback? onZoomEnd;<br><br>  const ResettableInteractiveViewer({<br>    super.key,<br>    required this.child,<br>    this.zoomEnabled = true,<br>    this.onZoomStart,<br>    this.onZoomEnd,<br>  });<br><br>  @override<br>  State&lt;ResettableInteractiveViewer&gt; createState() =&gt;<br>      _ResettableInteractiveViewerState();<br>}<br><br>class _ResettableInteractiveViewerState<br>    extends State&lt;ResettableInteractiveViewer&gt; {<br>  final _controller = TransformationController();<br><br>  Matrix4 _initialMatrix = Matrix4.identity();<br>  bool _zoomEnabled = true;<br><br>  bool _isZoomInProgress = false;<br>  double _scale = 1;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _zoomEnabled = widget.zoomEnabled;<br>  }<br><br>  @override<br>  void didUpdateWidget(covariant ResettableInteractiveViewer oldWidget) {<br>    if (widget.zoomEnabled != oldWidget.zoomEnabled) {<br>      _zoomEnabled = widget.zoomEnabled;<br>    }<br>    super.didUpdateWidget(oldWidget);<br>  }<br><br>  void _onInteractionStart(ScaleStartDetails details) {<br>    if (_isZoomInProgress) return;<br><br>    _initialMatrix = _controller.value;<br>  }<br><br>  void _onInteractionEnd(ScaleEndDetails details) {<br>    if (details.pointerCount &gt;= 2) return;<br>    if (!_isZoomInProgress) return;<br><br>    _setZoomEnd();<br>    _controller.value = _initialMatrix;<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return InteractiveViewer(<br>      onInteractionStart: _onInteractionStart,<br>      onInteractionUpdate: _onInteractionUpdate,<br>      onInteractionEnd: _onInteractionEnd,<br>      panEnabled: _zoomEnabled,<br>      scaleEnabled: _zoomEnabled,<br>      transformationController: _controller,<br>      child: widget.child,<br>    );<br>  }<br><br>  void _onInteractionUpdate(ScaleUpdateDetails details) {<br>    _scale = details.scale;<br><br>    if (_scale &gt; 1 &amp;&amp; !_isZoomInProgress) {<br>      _isZoomInProgress = true;<br>      widget.onZoomStart?.call();<br>    } else if (_scale &lt;= 1 &amp;&amp; _isZoomInProgress) {<br>      _setZoomEnd();<br>    }<br>  }<br><br>  void _setZoomEnd() {<br>    _scale = 1;<br>    _isZoomInProgress = false;<br>    widget.onZoomEnd?.call();<br>  }<br><br>  @override<br>  void dispose() {<br>    _controller.dispose();<br>    super.dispose();<br>  }<br>}</pre><p><strong>2. Use the Widget:</strong></p><pre>ResettableInteractiveViewer(<br>          onZoomStart: () =&gt; print(&#39;Zoom started&#39;),<br>          onZoomEnd: () =&gt; print(&#39;Zoom ended&#39;),<br>          child: Center(<br>            child: Container(<br>                width: 150,<br>                height: 150,<br>                color: Colors.orange),<br>          ),<br>        )</pre><p>As a result we get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*greY-Kmi3HgcEH_ilBQPGA.gif" /></figure><h4><strong>Conclusion</strong></h4><p>Creating a resettable pinch-to-zoom widget enhances usability significantly. The provided implementation offers clear and intuitive interactions, ensuring your app remains responsive and visually appealing after detailed interactions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20542246e9b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Add Shadows to Custom-Shaped Widgets in Flutter]]></title>
            <link>https://medium.com/@valerii.novykov/how-to-add-shadows-to-custom-shaped-widgets-in-flutter-839edf1a4453?source=rss-41dbaf902a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/839edf1a4453</guid>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <dc:creator><![CDATA[Valerii Novykov]]></dc:creator>
            <pubDate>Thu, 12 Jun 2025 08:21:30 GMT</pubDate>
            <atom:updated>2025-06-12T08:21:30.380Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*762K1JIcJ5BKYwgkkfwTew.png" /></figure><p>When designing Flutter applications, developers often need to create widgets with non-standard shapes, such as various geometric or irregular shapes. However, applying shadows to these shapes can pose challenges. A common method to alter a widget’s shape is using <strong>ClipPath</strong>, but when shadows are needed, this approach often doesn’t yield the expected results. Here’s how you can correctly add shadows to custom-shaped widgets using <strong>ShapeBorder</strong> and <strong>ShapeDecoration</strong>.</p><h4><strong>Introduction</strong></h4><p>If you’ve ever tried applying shadows to a custom-shaped widget, you might have encountered the frustration of shadows being clipped. This common problem arises because shadows are typically clipped alongside the content when using ClipPath. In this guide, I’ll walk you through a clean solution using <strong>ShapeBorder</strong> to apply shadows that follow the contour of your custom shape perfectly.</p><h4><strong>Problem Scenario</strong></h4><p>Imagine you want to create a triangle widget with a soft shadow around it. Initially, you might use a <strong>CustomClipper</strong> like this:</p><pre>class TriangleClipper extends CustomClipper&lt;Path&gt; {<br>  @override<br>  Path getClip(Size size) {<br>    final path = Path();<br><br>    path.moveTo(size.width / 2, 0);<br>    path.lineTo(size.width, size.height);<br>    path.lineTo(0, size.height);<br>    path.close();<br><br>    return path;<br>  }<br><br>  @override<br>  bool shouldReclip(covariant TriangleClipper oldClipper) =&gt; false;<br>}</pre><p>However, applying a shadow directly to the clipped widget doesn’t work:</p><pre>ClipPath(<br>            clipper: TriangleClipper(),<br>            child: Container(<br>              height: 200,<br>              width: 200,<br>              decoration: BoxDecoration(<br>                color: Colors.orange,<br>                boxShadow: [<br>                  BoxShadow(<br>                    color: Colors.black.withValues(alpha: 0.5),<br>                    blurRadius: 20,<br>                  ),<br>                ],<br>              ),<br>            ),<br>          )</pre><p>This results in the shadow being clipped away entirely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*FEPmIOY0kFWJo35uq9vxXQ.png" /></figure><p>This approach also fails when applying shadows to the parent widget, resulting in the shadow displaying incorrectly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*BNCFlyzR3Axy6OLyTr2ZkA.png" /></figure><h4><strong>Solution Overview</strong></h4><p>To achieve correctly rendered shadows around custom shapes, use <strong>ShapeBorder</strong> with <strong>ShapeDecoration</strong>. This method respects the shape boundaries, properly rendering the shadow.</p><h4><strong>Implementation Steps</strong></h4><p><strong>1. Create a Custom ShapeBorder:</strong></p><pre>class TriangleBorder extends ShapeBorder {<br>  const TriangleBorder();<br><br>  @override<br>  EdgeInsetsGeometry get dimensions =&gt; EdgeInsets.zero;<br><br>  @override<br>  Path getOuterPath(Rect rect, {TextDirection? textDirection}) =&gt;<br>      _createTrianglePath(rect);<br><br>  @override<br>  Path getInnerPath(Rect rect, {TextDirection? textDirection}) =&gt;<br>      _createTrianglePath(rect);<br><br>  Path _createTrianglePath(Rect rect) {<br>    final path = Path();<br><br>    path.moveTo((rect.left + rect.width / 2), rect.top);<br>    path.lineTo(rect.right, rect.bottom);<br>    path.lineTo(rect.left, rect.bottom);<br>    path.close();<br><br>    return path;<br>  }<br><br>  @override<br>  void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {}<br><br>  @override<br>  ShapeBorder scale(double t) =&gt; this;<br>}</pre><p><strong>2. Apply the ShapeDecoration:</strong></p><pre>Container(<br>            width: 200,<br>            height: 200,<br>            decoration: ShapeDecoration(<br>              color: Colors.orange,<br>              shape: const TriangleBorder(), // Custom shape<br>              shadows: [<br>                BoxShadow(<br>                  color: Colors.black.withValues(alpha: 0.5),<br>                  blurRadius: 20,<br>                ),<br>              ],<br>            ),<br>          ),</pre><p>As a result we get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*bwoCf8kzWjvMh7cpUukR5A.png" /></figure><h4><strong>Conclusion</strong></h4><p>Using ShapeBorder and ShapeDecoration provides a robust solution for rendering shadows around custom-shaped widgets, overcoming the limitations posed by traditional clipping methods. This technique ensures your custom designs maintain a polished and professional appearance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=839edf1a4453" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Measure Text Sizes Dynamically in Flutter Using a Convenient Extension]]></title>
            <link>https://medium.com/@valerii.novykov/how-to-measure-text-sizes-dynamically-in-flutter-using-a-convenient-extension-08a8aa6ea22e?source=rss-41dbaf902a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/08a8aa6ea22e</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <dc:creator><![CDATA[Valerii Novykov]]></dc:creator>
            <pubDate>Wed, 11 Jun 2025 07:58:27 GMT</pubDate>
            <atom:updated>2025-06-11T07:58:27.850Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jRZTih1o2QlndDXUf1-vuw.png" /></figure><p>When developing Flutter apps, especially ones supporting multiple languages or dynamic content, one common challenge is handling varying text lengths and styles. UI elements such as buttons, titles, and labels can significantly differ in size depending on language translations or dynamic data. How can we adjust layouts effectively before the text actually renders?</p><p>In this article, we’ll create a convenient Flutter extension that calculates the size of text dynamically, allowing you to adjust UI layouts proactively.</p><h4><strong>Background</strong></h4><p>In Flutter, text measurement is usually performed by the <strong>TextPainter</strong> class. It provides precise metrics about how text would render with specified styles and constraints. However, repeatedly configuring TextPainter can become cumbersome.</p><p>An elegant solution is to encapsulate this functionality into an extension method on BuildContext, simplifying your layout logic significantly.</p><h4><strong>Problem Scenario</strong></h4><p>Consider a scenario where your app supports multiple languages:</p><ul><li>English: “Sign Up”</li><li>German: “Registrieren”</li></ul><p>These translations differ substantially in length, potentially breaking your UI if it’s not designed for dynamic text sizes.</p><h4><strong>Solution Overview</strong></h4><p>We’ll create a <strong>TextMetrics</strong> extension on <strong>BuildContext</strong> that simplifies measuring text dimensions before rendering, allowing you to dynamically adjust your layouts.</p><h4><strong>Implementation Steps</strong></h4><p><strong>1. Create the Extension</strong></p><pre>extension TextMetrics on BuildContext {<br>  /// Retrieves the width of the text as a [double].<br>  ///<br>  /// This method provides a convenient way to get just the width of the text,<br>  /// using the same parameters as [getTextSize].<br>  ///<br>  /// The [text] parameter is the string of text to measure.<br>  /// The [maxLines] parameter specifies the maximum number of lines for the text.<br>  /// The [maxWidth] parameter sets the maximum width the text can occupy. Defaults to [double.infinity].<br>  /// The [style] parameter is the [TextStyle] used to style the text.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// double textWidth = context.getTextWidth(&#39;Hello World&#39;, style: TextStyle(fontSize: 16.0));<br>  /// ```<br>  double getTextWidth(String text,<br>      {int? maxLines, double maxWidth = double.infinity, TextStyle? style}) {<br>    return getTextSize(text,<br>            style: style, maxLines: maxLines, maxWidth: maxWidth)<br>        .width;<br>  }<br><br>  /// Retrieves the size of the text as a [Size] object.<br>  ///<br>  /// This method calculates the size of the given text with the specified [TextStyle],<br>  /// potentially limiting it to a certain number of lines and a maximum width.<br>  ///<br>  /// The [text] parameter is the string of text to measure. If null, defaults to measuring an empty string.<br>  /// The [maxLines] parameter specifies the maximum number of lines for the text.<br>  /// The [maxWidth] parameter sets the maximum width the text can occupy. Defaults to [double.infinity].<br>  /// The [style] parameter is the [TextStyle] used to style the text.<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// Size textSize = context.getTextSize(&#39;Hello World&#39;, style: TextStyle(fontSize: 16.0));<br>  /// ```<br>  Size getTextSize(String? text,<br>      {int? maxLines, double maxWidth = double.infinity, TextStyle? style}) {<br>    final tp = getTextPainter(text,<br>        style: style, maxLines: maxLines, maxWidth: maxWidth);<br><br>    return tp.size;<br>  }<br><br>  /// Creates a [TextPainter] with the given parameters and styles.<br>  ///<br>  /// This method sets up a [TextPainter] that can be used to measure text size,<br>  /// perform layout, and paint text on the canvas.<br>  ///<br>  /// The [text] parameter is the string of text to measure. If null, defaults to measuring an empty string.<br>  /// The [maxLines] parameter specifies the maximum number of lines for the text.<br>  /// The [maxWidth] parameter sets the maximum width the text can occupy. Defaults to [double.infinity].<br>  /// The [style] parameter is the [TextStyle] used to style the text.<br>  /// Example:<br>  /// ```dart<br>  /// TextPainter tp = context.getTextPainter(&#39;Hello World&#39;, style: TextStyle(fontSize: 16.0));<br>  /// ```<br>  TextPainter getTextPainter(String? text,<br>      {int? maxLines, double maxWidth = double.infinity, TextStyle? style}) {<br>    final defaultTextStyle = DefaultTextStyle.of(this).style;<br><br>    final effectiveStyle = style?.copyWith(<br>          height: style.height ?? defaultTextStyle.height,<br>          letterSpacing: style.letterSpacing ?? defaultTextStyle.letterSpacing,<br>        ) ??<br>        defaultTextStyle;<br><br>    return TextPainter(<br>      text: TextSpan(text: text ?? &#39;&#39;, style: effectiveStyle),<br>      maxLines: maxLines,<br>      textDirection: TextDirection.ltr,<br>      textScaler: MediaQuery.textScalerOf(this),<br>    )..layout(maxWidth: maxWidth);<br>  }<br>}</pre><p><strong>2. Use the Extension</strong></p><p>You can now effortlessly measure text within any widget build method:</p><pre>final buttonTextWidth = context.getTextWidth(<br>  &#39;Registrieren&#39;,<br>  style: Theme.of(context).textTheme.labelLarge,<br>);</pre><h4><strong>Conclusion</strong></h4><p>By encapsulating text measurement logic into a simple, reusable extension, you streamline handling dynamic content, enhancing your Flutter app’s UI adaptability. This approach reduces bugs related to text overflow and layout inconsistencies, ensuring a consistent, polished user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08a8aa6ea22e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a Flexible Mock Text Generator Utility in Dart for UI Testing]]></title>
            <link>https://medium.com/@valerii.novykov/how-to-create-a-flexible-mock-text-generator-utility-in-dart-for-ui-testing-ac924c6a63c7?source=rss-41dbaf902a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac924c6a63c7</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Valerii Novykov]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 08:24:00 GMT</pubDate>
            <atom:updated>2025-06-10T08:24:00.694Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIR5SEU7mNDL-lySRiUkwg.png" /></figure><p>When building UI applications, especially in Flutter, developers often need placeholder or mock text to visualize how their interfaces handle different text lengths and structures. Hardcoding static strings can be tedious and inflexible. What if you need paragraphs of varied lengths or a specific number of sentences? A utility that can generate mock text dynamically, with customizable length and structure, can save time and make testing more realistic.</p><p>In this article, we’ll create a Dart utility class — <strong>MockTextGenerator</strong> — that lets you generate mock text as words, sentences, paragraphs, or by exact length. We’ll also demonstrate how to use it effectively in your Flutter UI development.</p><h4><strong>Background: Why Use a Mock Text Generator?</strong></h4><p>Mock text, often called “Lorem Ipsum,” is used as filler content during UI design and development. It helps you:</p><ul><li>Test how text fits in layout widgets (e.g., cards, lists, dialogs).</li><li>Ensure text wrapping, truncation, and scrolling behave correctly.</li><li>Simulate real user content before backend integration.</li></ul><p>Using a flexible generator avoids repetitive manual copying of placeholder strings and lets you tailor mock content precisely to your testing needs.</p><h4><strong>Problem Scenario: Limitations of Hardcoded Text</strong></h4><p>Imagine you’re designing a card widget that can contain a variable number of sentences. Hardcoding a single string limits your ability to test different UI states:</p><pre>const hardcodedText = &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&quot;;</pre><ul><li>Too short? The card looks empty.</li><li>Too long? You need to manually add or remove sentences.</li><li>No control over paragraphs or exact text length.</li></ul><p>This approach slows down design iteration and makes automated UI tests less reliable.</p><h4><strong>Solution Overview: MockTextGenerator Utility</strong></h4><p>We’ll build a Dart class with methods to generate:</p><ul><li>A specified number of words.</li><li>A specified number of sentences.</li><li>A text string up to an exact character length.</li><li>A specified number of paragraphs.</li></ul><p>This utility will use a predefined list of words and assemble text randomly with proper capitalization and punctuation, providing natural-looking placeholder content.</p><h4><strong>Implementation Steps</strong></h4><p><strong>1. Define an enum to specify generation type</strong></p><pre>enum MockTextType {<br>  /// Generate a specified number of words.<br>  words,<br><br>  /// Generate a specified number of sentences.<br>  sentences,<br><br>  /// Generate text up to a specified length.<br>  length,<br><br>  /// Generate a specified number of paragraphs.<br>  paragraphs<br>}</pre><p><strong>2. Create the main MockTextGenerator class with a static generate method</strong></p><pre>/// A utility class for generating mock text data of various types.<br>/// This class can generate words, sentences, paragraphs, or text of a specified length.<br>class MockTextGenerator {<br>  static final Random _random = Random();<br><br>  /// Generates mock text based on the specified [type] and [length].<br>  ///<br>  /// The [length] argument defines the number of words, sentences, paragraphs,<br>  /// or the length of the text, depending on the [type] argument.<br>  ///<br>  /// Returns the generated mock text as a [String].<br>  ///<br>  /// Example:<br>  /// ```dart<br>  /// String mockWords = MockTextGenerator.generate(type: MockTextType.words, length: 5);<br>  /// print(mockWords); // Lorem ipsum dolor sit amet<br>  /// ```<br>  static String generate({<br>    MockTextType type = MockTextType.words,<br>    int length = 50,<br>  }) {<br>    switch (type) {<br>      case MockTextType.words:<br>        return _generateWords(length);<br>      case MockTextType.sentences:<br>        return _generateSentences(length);<br>      case MockTextType.length:<br>        return _generateByLength(length);<br>      case MockTextType.paragraphs:<br>        return _generateParagraphs(length);<br>    }<br>  }<br><br>  static String _generateWords(int wordCount) {<br>    return List.generate(wordCount, (_) =&gt; _getRandomWord()).join(&#39; &#39;);<br>  }<br><br>  static String _generateByLength(int textLength) {<br>    String result = &#39;&#39;;<br><br>    while (result.length &lt; textLength) {<br>      final word = _getRandomWord();<br><br>      if (_canAppendWholeWord(result, word, textLength)) {<br>        result = _appendWord(result, word);<br>      } else {<br>        result = _appendPartialWord(result, word, textLength);<br>        break;<br>      }<br>    }<br><br>    return result;<br>  }<br><br>  static bool _canAppendWholeWord(String result, String word, int maxLength) {<br>    final newLength = result.length + word.length + (result.isEmpty ? 0 : 1);<br>    return newLength &lt;= maxLength;<br>  }<br><br>  static String _appendWord(String result, String word) {<br>    return result + (result.isEmpty ? &#39;&#39; : &#39; &#39;) + word;<br>  }<br><br>  static String _appendPartialWord(String result, String word, int maxLength) {<br>    final diff = maxLength - result.length;<br><br>    return result +<br>        (result.isEmpty ? &#39;&#39; : &#39; &#39;) +<br>        word.substring(0, diff - (result.isEmpty ? 0 : 1));<br>  }<br><br>  static String _generateParagraphs(int paragraphCount) {<br>    final paragraphs =<br>        List.generate(paragraphCount, (_) =&gt; _generateParagraph());<br><br>    return paragraphs.join(&#39;\n\n&#39;);<br>  }<br><br>  static String _generateParagraph() {<br>    final sentenceCount = _random.nextInt(5) + 3; // 3 - 7 sentences<br><br>    return _generateSentences(sentenceCount);<br>  }<br><br>  static String _generateSentences(int sentenceCount) {<br>    final sentences = List.generate(sentenceCount, (_) =&gt; _generateSentence());<br><br>    return sentences.join(&#39; &#39;);<br>  }<br><br>  static String _generateSentence() {<br>    final wordCount = _random.nextInt(8) + 5; // 5 - 12 words<br><br>    final sentence =<br>        List.generate(wordCount, (_) =&gt; _getRandomWord()).join(&#39; &#39;);<br><br>    return &#39;${sentence.capitalizeFirst()}.&#39;;<br>  }<br><br>  static String _getRandomWord() {<br>    return _words[_random.nextInt(_words.length)];<br>  }<br>}<br><br>const _words = [<br>  &#39;Lorem&#39;,<br>  &#39;ipsum&#39;,<br>  &#39;dolor&#39;,<br>  &#39;sit&#39;,<br>  &#39;amet&#39;,<br>  &#39;consectetur&#39;,<br>  &#39;adipiscing&#39;,<br>  &#39;elit&#39;,<br>  &#39;sed&#39;,<br>  &#39;do&#39;,<br>  &#39;eiusmod&#39;,<br>  &#39;tempor&#39;,<br>  &#39;incididunt&#39;,<br>  &#39;ut&#39;,<br>  &#39;labore&#39;,<br>  &#39;et&#39;,<br>  &#39;dolore&#39;,<br>  &#39;magna&#39;,<br>  &#39;aliqua&#39;,<br>  &#39;Ut&#39;,<br>  &#39;enim&#39;,<br>  &#39;ad&#39;,<br>  &#39;minim&#39;,<br>  &#39;veniam&#39;,<br>  &#39;quis&#39;,<br>  &#39;nostrud&#39;,<br>  &#39;exercitation&#39;,<br>  &#39;ullamco&#39;,<br>  &#39;laboris&#39;,<br>  &#39;nisi&#39;,<br>  &#39;ut&#39;,<br>  &#39;aliquip&#39;,<br>  &#39;ex&#39;,<br>  &#39;ea&#39;,<br>  &#39;commodo&#39;,<br>  &#39;consequat&#39;,<br>  &#39;Duis&#39;,<br>  &#39;aute&#39;,<br>  &#39;irure&#39;,<br>  &#39;dolor&#39;,<br>  &#39;in&#39;,<br>  &#39;reprehenderit&#39;,<br>  &#39;in&#39;,<br>  &#39;voluptate&#39;,<br>  &#39;velit&#39;,<br>  &#39;esse&#39;,<br>  &#39;cillum&#39;,<br>  &#39;dolore&#39;,<br>  &#39;eu&#39;,<br>  &#39;fugiat&#39;,<br>  &#39;nulla&#39;,<br>  &#39;pariatur&#39;,<br>  &#39;Excepteur&#39;,<br>  &#39;sint&#39;,<br>  &#39;occaecat&#39;,<br>  &#39;cupidatat&#39;,<br>  &#39;non&#39;,<br>  &#39;proident&#39;,<br>  &#39;sunt&#39;,<br>  &#39;in&#39;,<br>  &#39;culpa&#39;,<br>  &#39;qui&#39;,<br>  &#39;officia&#39;,<br>  &#39;deserunt&#39;,<br>  &#39;mollit&#39;,<br>  &#39;anim&#39;,<br>  &#39;id&#39;,<br>  &#39;est&#39;,<br>  &#39;laborum&#39;<br>];<br><br>extension _Capitalize on String {<br>  String capitalizeFirst() {<br>    if (isEmpty) {<br>      return this;<br>    }<br><br>    return &quot;${this[0].toUpperCase()}${length &gt; 1 ? substring(1).toLowerCase() : &#39;&#39;}&quot;;<br>  }<br>}</pre><p><strong>3. Use the generator in your widgets</strong></p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_utils/flutter_utils.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      debugShowCheckedModeBanner: false,<br>      home: MockTextContent(),<br>    );<br>  }<br>}<br><br>class MockTextContent extends StatelessWidget {<br>  const MockTextContent({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: SafeArea(<br>        child: Padding(<br>          padding: const EdgeInsets.all(16.0),<br>          child: SingleChildScrollView(<br>            child: Column(<br>              spacing: 15.0,<br>              children: [<br>                _buildTitle(&#39;10 words mock text:&#39;),<br>                Text(<br>                  MockTextGenerator.generate(<br>                    type: MockTextType.words,<br>                    length: 10,<br>                  ),<br>                ),<br>                _buildTitle(&#39;3 sentences mock text:&#39;),<br>                Text(<br>                  MockTextGenerator.generate(<br>                    type: MockTextType.sentences,<br>                    length: 3,<br>                  ),<br>                ),<br>                _buildTitle(&#39;50 characters mock text:&#39;),<br>                Text(<br>                  MockTextGenerator.generate(<br>                    type: MockTextType.length,<br>                    length: 50,<br>                  ),<br>                ),<br>                _buildTitle(&#39;2 paragraphs mock text:&#39;),<br>                Text(<br>                  MockTextGenerator.generate(<br>                    type: MockTextType.paragraphs,<br>                    length: 2,<br>                  ),<br>                ),<br>              ],<br>            ),<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br><br>  Widget _buildTitle(String title) {<br>    return Text(<br>      title,<br>      style: const TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),<br>    );<br>  }<br>}</pre><p>As a result we get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*f4Wyy-Fqv987hC_WR59rUw.png" /></figure><h4><strong>Conclusion</strong></h4><p>Creating a flexible mock text generator helps speed up UI development and testing by producing realistic, variable placeholder content tailored to your needs. The <strong>MockTextGenerator</strong> class shown here offers multiple modes of generation and can be easily extended with new features such as custom word lists or localization.</p><p>This utility makes UI testing more robust and design iterations faster, helping you focus on delivering polished user experiences.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac924c6a63c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Display Custom Error Widgets for Flutter Text Fields]]></title>
            <link>https://medium.com/@valerii.novykov/how-to-display-custom-error-widgets-for-flutter-text-fields-e47db6f88de5?source=rss-41dbaf902a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/e47db6f88de5</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter-tips]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Valerii Novykov]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 08:40:22 GMT</pubDate>
            <atom:updated>2025-06-09T08:40:22.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DODUPQYUVmz8o7Lj0iHD3A.png" /></figure><p>When building forms in Flutter, the default error message display for text fields isn’t always sufficient. For an improved user experience, designs often call for customized error widgets, such as including an icon alongside the error text. In this article, we’ll explore how you can easily achieve this using Flutter’s <strong>FormField</strong> widget to customize error display specifically for text fields.</p><h4><strong>The Problem Scenario</strong></h4><p>Imagine you’re creating a username input field within a form. The design requires displaying an error message with a distinctive icon whenever the input doesn’t meet validation rules. Unfortunately, Flutter’s default TextField widget doesn’t provide this functionality directly.</p><h4><strong>Solution Overview</strong></h4><p>The solution involves wrapping the <strong>TextField</strong> inside a <strong>FormField</strong>, which allows custom error handling through its <strong>errorBuilder</strong> callback. This gives you control over how text field errors are displayed, ensuring the design aligns perfectly with your requirements.</p><h4><strong>Implementation Steps</strong></h4><p><strong>1. Creating the Custom Text Field</strong></p><p>Define a custom widget UserNameField that uses <strong>FormField</strong> internally. Use <strong>validator</strong> for validation logic and <strong>errorBuilder</strong> for custom error widget creation.</p><pre>class UserNameField extends StatelessWidget {<br>  const UserNameField({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return FormField&lt;String&gt;(<br>      validator: _validateUsername, // Validation function for the username<br>      errorBuilder: _buildErrorWidget, // Custom error widget builder<br>      builder: (state) {<br>        return Column(<br>          children: [<br>            TextField(<br>              decoration: _buildInputDecoration(),<br>              onChanged: state.didChange, // Update field state value on change<br>            ),<br>            if (_isErrorVisible(state))<br>              // Show custom error widget if there&#39;s an error<br>              state.widget.errorBuilder!(context, state.errorText!),<br>          ],<br>        );<br>      },<br>    );<br>  }<br><br>  String? _validateUsername(String? value) {<br>    return (value != null &amp;&amp; value.trim().length &gt;= 3)<br>        ? null<br>        : &#39;Username must be at least 3 characters&#39;;<br>  }<br><br>  Widget _buildErrorWidget(BuildContext context, String error) {<br>    return Row(<br>      spacing: 5,<br>      children: [<br>        const Icon(Icons.warning_rounded, color: Colors.red),<br>        Expanded(<br>          child: Text(error, style: const TextStyle(color: Colors.red)),<br>        ),<br>      ],<br>    );<br>  }<br><br>  InputDecoration _buildInputDecoration() {<br>    return const InputDecoration(<br>      labelText: &#39;Username&#39;,<br>      border: OutlineInputBorder(),<br>    );<br>  }<br><br>  bool _isErrorVisible(FormFieldState&lt;String&gt; state) {<br>    return state.hasError &amp;&amp; state.widget.errorBuilder != null;<br>  }<br>}</pre><p><strong>2. Integrating the Custom Text Field</strong></p><p>In your main form, you can now use the custom UserNameField widget to handle validation and display custom error messages:</p><pre>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      debugShowCheckedModeBanner: false,<br>      home: Scaffold(<br>        body: Padding(<br>          padding: const EdgeInsets.all(16.0),<br>          child: Center(child: UsernameForm()),<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>class UsernameForm extends StatefulWidget {<br>  const UsernameForm({super.key});<br><br>  @override<br>  State&lt;UsernameForm&gt; createState() =&gt; _UsernameFormState();<br>}<br><br>class _UsernameFormState extends State&lt;UsernameForm&gt; {<br>  final _formKey = GlobalKey&lt;FormState&gt;();<br><br>  bool _autoValidate = false;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Form(<br>      key: _formKey,<br>      autovalidateMode: _autoValidate<br>          ? AutovalidateMode.always<br>          : AutovalidateMode.disabled,<br>      child: Column(<br>        mainAxisSize: MainAxisSize.min,<br>        spacing: 16,<br>        children: [<br>          UserNameField(), // Username field with custom error widget<br>          ElevatedButton(onPressed: _onSubmit, child: const Text(&#39;Submit&#39;)),<br>        ],<br>      ),<br>    );<br>  }<br><br>  void _onSubmit() {<br>    if (_formKey.currentState?.validate() ?? false) {<br>      ScaffoldMessenger.of(<br>        _formKey.currentContext!,<br>      ).showSnackBar(const SnackBar(content: Text(&#39;Form is valid&#39;)));<br>    } else {<br>      setState(() {<br>        _autoValidate = true;<br>      });<br>    }<br>  }<br>}</pre><p>As a result we get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*hycLdA6UWJObT8v0i8xWVA.png" /></figure><h4><strong>Conclusion</strong></h4><p>Using <strong>FormField</strong> with a custom <strong>errorBuilder</strong> is a powerful method to enhance error handling specifically for Flutter text fields. This approach ensures your forms maintain design consistency and provide a more intuitive user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e47db6f88de5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>