Flutter is a framework from Google to build cross platform applications. This means you can write code once and it will run on iOS and Android devices. Flutter consists of many widgets, which can be used to construct a complete view.
In this post, I will demonstrate how you can make a reusable ratings widget in Flutter.
If you are interested, I have created a video associated with this article. You can watch the video using the link below. If you prefer reading then continue ahead.
Displaying the Stars
Start by adding a rating.dart file which will serve as our rating widget. Our first task is to display the stars on the page. The number of stars will depend on the user. This means a user can display 3 or 5 or even 10 stars. To accomplish this we make sure that the number of stars is a dependency to create an instance of the Rating class.
We have also made sure to provide a default value of 5 for maximumRating. This means 5 stars will be created if the maximumRating is not provided. Now, let’s move on to creating the stars.
Let’s take a look at the code below:
The _buildBody function is responsible for creating the entire body of the Rating widget. Inside the _buildBody we run a loop, based on the maximumRating. Within the loop we construct stars using _buildRatingStar function, which simply returns an Icon representing the star. The output is shown below:
Adding Gestures and Accessing Selected Rating
At present the rating stars are shown, but they don’t provide any interaction. The easiest way to add interaction to our Rating widget is to use Gesture widget. The Gesture widget can easily add gesture to the child widgets as shown below:
Run the app and tap on any of the stars. You will notice that the onTap gets invoked and prints “tapped” on the terminal. Next we need to store the selected rating and also notify the caller that a new rating has been selected. Let’s take a look at the code below:
We have updated the Rating constructor, which now requires a function onRatingSelected to be passed. The onRatingSelected function is a closure, which provides the current rating to the caller.
Also inside the _buildBody function, we call the onRatingSelected closure, which finally provides the value to the caller. Inside _buildRatingStar we updated the code to toggle between the selected star and a not selected star.
The code below is used in main.dart file which uses the Rating widget.
The result is shown below:
At present if you select a rating there is no way to remove or reset it. In this last section we will create a “Clear” button, which will allow the user to reset the rating.
As you can see in the above code, when the clear button is tapped it sets the _currentRating to 0 and also notify the caller with the new rating.
The final output is shown below:
If you are interested, you can watch the video associated with this article.
If you want to support my work then check out my Flutter and other courses on Udemy. Thanks!