Zooming with GestureDetector
In the previous post, I described how to create own chart using CustomPainter. Now I will go through adding zoom effect to the diagram using GestureDetector.
At first, let’s define our starting point. I have own StatelessWidget that contains CustomPaintwith own CustomPainter. The main widget receives a list of all entries and passes only those from last 31 days. CustomPainter gets a new list of entries and uses the main Widget’s constant number of days. What I would like to achieve is that when a user “zooms in” the X-axis (number of days) changes respectively.
If you are interested in detailed specifics, see full code.
. . .
The best tool to handle gestures in Flutter is (surprisingly) GestureDetector. In my case, I used two of its features: onScaleStart and onScaleUpdate. Also, I needed to changed ProgressChartto be StatefulWidget to store and change the number of days since it is not a const anymore. This is how it looks like:
How it works:
- When zoom gesture starts I store the current number of days.
- When zoom updates I get the scale and divide the previous number of days by it. Notice that I am changing only the current number of days, not the previous one. If I updated the starting point, the number of days would quickly go towards infinity or 0 depending on gesture.
- I added border value so max zoom is one week.
- At the end, I refactored ChartPainter to accept numberOfDays instead of referencing constant value.
. . .
After small adjustments to bottom labels, final effect looks like this:
Founder of Fidev
Flutter enthusiast since Alpha release in 2017. Believes that sharing is caring, which lead him to start a technical blog dedicated fo Flutter in its early days. Loves to see beautiful designs become real apps and is willing to help make it happen. Enjoys sunny beaches far from home.
Join the newsletter!
Join the newsletter to keep track with latest posts and get my special Widget to animate views' entrances without any hassle for FREE!
Check out other posts!
Have you ever struggled to integrate card payments into your mobile Flutter app? If so, today is your lucky day! In this post, I present how to use Stripe Checkout in the Flutter app without any hassle!
Have you ever developed a widget or a page and you wanted to make sure it works correctly in different scenarios but then it turned out that you can’t just reproduce all the cases you want to cover? Framy may solve such problems!