Star Rating Bar with Flutter Reactive Forms

Joan Pablo Jiménez
Flutter Community
Published in
3 min readOct 4, 2020
Reactive Forms

Reactive Forms is not just limited to common widgets in Forms like text inputs, dropdowns, sliders, and switches; you can easily create custom widgets that two-way binds to FormControls and create your own set of Reactive Widgets.

In this post, we will learn how to implement a Reactive Star Rating widget using Reactive Forms, and thus be able to create rich forms that can also collect information using a star rating bar.

To know more about Reactive Forms you can read my previous post Why use Reactive Forms in Flutter? or visit GitHub and pub repo. You can also read the wiki page Custom Reactive Widgets.

This is what we are going to achieve at the end of this post:

Reactive Star Rating Bar

We are not going to create a Star Rating Bar from zero, instead, we are going to use an existing widget and convert it into a Reactive Widget.

We will use the excellent plugin flutter_rating_bar and give it the ability to two-way binds with a FormControl.

Less talking and more coding ;)

flutter_rating_bar: ^3.0.1+1 was the last version at the time of the post.

Create our reactive widget, declare ReactiveStarRating, and extends from ReactiveFormField:

Then supply to the parent class the formControlName and the builder function:

Done, say hello to our new reactive widget ReactiveStarRating.

Wow but wait a minute, what just happened here, is that all? Yes, we are done with the reactive widget, but before we start using it, let me explain the above code a little bit.

These are the steps:

1- Extend from ReactiveFormField. This is a StatefulWidget that maintains the state and is bound with the FormControl.

2- Provide a builder function in the parent’s constructor (super). This function will return your inner widget, in this case, the RatingBar widget. The builder function will be called every time the FormControl changes its value.

3- Update the value of the FormControl with the method didChange method. Every time you want to update the value of the FormControl, call the didChange method of the ReactiveFormField passing the new value.

How use it?

We are almost done, now let’s consume our new ReactiveStarRating, we will also add some other reactive widgets that listen for changes in the FormControl just to visualize how they stay in sync with our new ReactiveStarRating:

And that’s it. This was a very simple example. I urge you to make the widget more configurable so that it allows you to change the background color of the stars and evaluate with a half star.

I hope you have enjoyed the post.

Thanks.

https://www.twitter.com/FlutterComm

--

--