Implement Reading Progress Bar using Flutter
Have you seen the progress bar that fills up as we scroll down the article we are reading? If not, then check now.
So, that looks freaking amazing and so intuitive, isn’t it?
Now, let’s dive into the quest of how to implement that reading progress bar using Flutter. Before that, let me inform you that I am going to implement this for mobile applications, so feel free to use this approach and implement it for any other screen you like.
Enough, of talking.
First of all, we need a screen with lots of words on it and of course, it should be scrollable.
For that, I have used HTML content and rendered that using flutter_widget_from_html_core.
Here’s, what it looks like.
Then, we will get some UI for the progress indicators. Well, for that I have used percent_indicator and added that to the bottom navigation bar property of the Scaffold widget. (Obviously, you can place it anywhere!)
Now, we will create an object of ScrollController and will assign that to the controller property of our scrollable widget(SingleChildScrollView or ListView).
Now, It’s time…
It’s time to create a progressValue variable, which will store the value of, how much we have scrolled through the screen and assign that to the percent property of the LinearPercentIndicator widget.
Finally, it’s time to add a listener to our scroll controller, to get the values of how much we have scrolled through the screen.
Let’s look at the implementation of Scrollcontroller, to know which properties we can use to get the values of how much the user has scrolled through the screen.
Using offset property we will get current position of how much we have scrolled through the screen. But that value will go higher than 100, so we will divide that offset value with maxScrollExtent property of position from scrollController. Here, position is object of ScrollPosition class.
Also, after assigning value to progressValue, add setState(), to rebuild the widget.
Here’s the output :
Voila!!!, we did it.
But, wait there’s two issues over here.
- It will throw an error when we scrolls up from the top, as the value we get from offset property will be negative and percent property only accepts positive value.
2. It will through an error when we scrolls down from the bottom, as the value we get from after division will be greater than 1.0 and percent property only accepts value from 0.0 to 1.0.
No Worries!!!
Here’s the quick fix for these issues.
Finally, we have implemented reading progress bar using Flutter.
Please, check out this git repo to look at full code and please do follow me on Github as well as here on Medium, too. Thank you!!!
I would love to read your responses for this article, so please do comment as well as all claps you will give me keeps me motivated to create more and share more with everyone.
See you, then Till next article.
Happy Fluttering!!!