The FilterPage consists of a series of tech domains that the user might be most interested in. You’ll let the user either show all the domains, or just filter down to one particular domain. To help with creating the FilterPage and keep its code nice and tidy, in this episode you’ll create a FilterWidget that displays a filter value. The FilterPage will then consist of a set of these filter widgets.
We’re going to be using a radio widget to allow the user to make a selection. A radio button allows the user to make one selection from a series of options.
Now Radio widgets don’t contain their own state so we’ll use the FilterWidget to maintain that state. The Radio button comes with two important properties. The first property is just called Value. The value is the actual value of the radio button. So if we had five options, you might set the value from one to five. The group value makes an association between a collection of radio buttons. This means our collection of five radio buttons will have different values but the same group value.
To get started, open your project in progress or download the sample project for this episode. We’ll start be creating a new filter widget. In the filter subfolder, create a new file called filter_widget.dart.
Once created, create a new stateless widget. Remember, just type ST and select stateless widget from the dropdown. Name it FilterWidget.
class FilterWidget extends StatelessWidget {
}
Make sure to import the material library.
import 'package:flutter/material.dart';
This widget will contain a few properties. First it will include a value. Remember, this is the backing value for each radio button.
final int value;
Next up, we have the group value for each radio button as well.
final int groupValue;
The onChanged property is notified when the user makes a selection from the radio group. This property will be set to the selection.
final ValueChanged<int?> onChanged;
Finally, our text property represents the filter’s name.
final String text;
Now with all of our properties in place, we need to update our constructor. All of these properties with exception of the key will be required.
const FilterWidget(
{Key? key,
required this.value,
required this.groupValue,
required this.onChanged,
required this.text})
: super(key: key);
Now for the build method. We will create a Radio button and place a label next to it. The text label is just the name of the button.
@override
Widget build(BuildContext context) {
return Row(
children: [
Radio(
value: value,
groupValue: groupValue,
onChanged: onChanged,
),
Text(
text,
style: const TextStyle(fontSize: 16.0),
),
],
);
}
The value, groupValue, and onChangedValue callback are passed along to the Radio widget, and the text is displayed in a text widget. So now we have our filter widget ready to go. In the next episode, you’ll use your new FilterWidget to build out the FilterPage.