Working with Reusable Radio Button Widgets in Flutter.

Hrishikesh Deshmukh
2 min readDec 28, 2019

--

Ever stuck in a app where :

  1. You have a section that lets a user select one radio button,
  2. There are so many such sections.

To solve this problem, flutter rescues you with its power of creating re-usable custom widgets. So lets get started.

After you have Created a new Flutter project, go ahead and make a new file, we will name it- DualRadioButtonCard.dart.

make a Stateful class named DualRadioButtonCard, to look like this:

Let us understand thee parameters:

  1. title: The title for the card widget
  2. option1: String that represents first choice
  3. option2: String that represents the second choice
  4. onChanged: This is a function that shall detect a integer value on our tapping of the radio button.

Lets now implement the State class — DualRadioOptionCardState

We have declared a variable of integer type that would determine our selection. Let’s set it to -1, such that no option is selected initially.

Here, we have a class named SizeConfig, which will help us determine the dimensions of screens such that our reusable widget would scale itself according to the device on which it is being run.

In the build method, we implement a Card widget with Row, having two Radio widgets. and Text widgets, that would describe the two respective radio buttons.

Assign integer values to each radio button. The groupValue property determines the value of selected Radiobutton from a collection of buttons. we assign it as the selectedValue variable. Finally, we pass the onChanged function to the radio button, such that it can set the current selection value.

The DualRadioButton.dart file should now look like this:

Lets dive into our main.dart file:

In the build Method of our HomePageState, lets place our DualRadioButtonCard in Center by using a center widget and pass the necessary title,options and selected value. Don’t forget to implement the onChanged function, which will take the integer value , which we will use to set the value of the group of radio buttons.

In this way, you can simply cal DualRadioButton in any build method to use them with your custom names of options,titles and function bodies.

Go ahead, and run the app, to see your custom Radio button Card in action!!!

That’s it for this post, please let me know if this post needs some improvement.I can be reached on Twitter, LinkedIn for updates, queries and suggestions on my posts.

I Wish all my readers a very Happy New Year in advance and until next time,

#HappyCoding and #HappyLearning !!!

--

--