Scrolling canvas 2 direction for Flutter

Bảo Gia
Bảo Gia
Sep 3, 2018 · 3 min read

Hi guys, today, I’ll show you how to create a two-dimensional scroll bar for a canvas. With Flutter, we can easily create custom list-view by only-one canvas.

1. Create list-view canvas:

I n fact, the list-view in video is a canvas. To create it, we need to define a ColorPainter class extends the CustomPainter class and override two methods: paint, shouldRepaint.

  • paint: Called whenever the object needs to paint. The given [Canvas] has its coordinate space configured such that the origin is at the top left of the box. The area of the box is the size of the [size] argument.

Now, we need to paint rows (name of color, list color) based on the input of position, size, color, etc. In some cases we need to calculate these values, specifically:

In method paintNameColor, we will define the style, span, and paint names of the colors.

In method paintListColor, we will create a horizontal-list-view by color-squares:

  • shouldRepaint: Called whenever a new instance of the custom painter delegate class is provided to the [RenderCustomPaint] object, or any time that a new [CustomPaint] object is created with a new instance of the custom painter delegate class (which amounts to the same thing, because the latter is implemented in terms of the former).

Variables: colors, offsets are input, which determines color, name, position (make scrolling-function).

2. Create color board:

The next, we will create a basic stateful-widget, ColorBoard, which contain our scrolling-canvas. In the state class, we build:

As we see, the CustomerPaint contained by Listener. Here, we focus on onPointerUp, onPointerMove method.

  • onPointerUp, we will handle pointer that triggered an [onPointerDown] is no longer in contact with the screen.
  • onPointerMove, we will handle pointer that triggered an [onPointerDown] changes position.

Okay, What is onScrollVerical, onScrollHorizontal, resetScrollState, velocity ?? I will show all in my post later.

3. Call color board anywhere

Finally, we can easily build a scrolling-color-board. Of course, it can scroll two directions: ColorBoard(colors: _colors).

And my repository:

Thanks for reading !

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade