Flutter — paint dashed line (both horizontal and vertical axis)

Lets create a widget that rendering horizontal or vertical dashed line having these features:

  • Paint style will be customizable. User will be able to define its own paint style.
  • Length of dash and gap will be customizable.
  • And most importantly, the line will be symmetric with respect to the midpoint of line (mathematically formulated) for any size.

If you interested in zigzag line, please read this article Flutter — paint zigzagline (both horizontal and vertical axis)

Let’s start designing an abstract line class, we will extend line pattern classes from this class:

Now, let’s extend two line pattern class: solid and dashed. Our focus will be on dashed line, but in some cases we will use solid line painter which with more performance (always escape from unnecessary calculation).

Let’s design our line painter class — Line painter will take line definition (which is solid or dashed) and the paint style as parameter to produce the requested line.

Let’s design our AdvancedLine widget. Please notice that, our line painter class rendering only horizontal lines, if user requests vertical line, AdvancedLine widget will rotate the rendered horizontal line 90 degrees.

Let’s build some dashed line outputs:

  • The first line has been defined horizontally (inside 240 width Container) without custom Paint style, with default dash size and gap size. Flutter says for stroke width, ‘Defaults to 0.0, which correspond to a hairline width’.
  • The second line (has wrapped with ‘Expanded widget’, thus the width of the dashed line will be the width of the screen) has been defined with custom Paint stroke width. Please notice that the symmetry of line starting and ending.
  • The last line has been defined (inside 200 width Container) with custom dash size and gap size.

Lest change the Stroke Cap as round or square. ⚡ You can visit flutter documentation page about Stroke Cap types.

  • The first line has been defined with default Stroke Cap which is ‘butt’.
  • The second line is defined by the Stroke Cap ‘round’, the gap and dash sizes are equal to those of the first line. See the effect of changing the stroke cap.
  • The last line has been defined with Stroke Cap ‘square’ and inside Expanded Container.

Let’s build a vertical dashed line:

If you wonder that how i calculate symmetry of the dashed line, you can continue to read the article.

Lets see how figure Perfect size and Leap size from given arguments:

Best regards…

Java, Flutter — Dart Software Developer