How to solve this problem. When I select yes, only a textbox will appear, but the radio button does not look like select. When I select no textbox is still visible. I tried to find an example code but was unsuccessful. Sorry, this is my first time making a design like this. Please help.
code:
late String _selectyes;
void handleSelection(value) {
setState(() {
_selectyes = value;
_yes = value == _selectyes;
});
}
Container(
width: MediaQuery.of(context).size.width > 800
? 700
: MediaQuery.of(context).size.width,
padding: const EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: const EdgeInsets.only(bottom: 20, top: 20),
child: LinearPercentIndicator(
padding: const EdgeInsets.symmetric(horizontal: 0.0),
lineHeight: 20.0,
animationDuration: 3000,
percent: _completionPercentage,
animateFromLastPercent: true,
center: Text(
"$_stepno/1",
style: const TextStyle(color: Colors.white),
),
barRadius: const Radius.circular(5),
backgroundColor: Colors.grey,
progressColor: Colors.black,
),
),
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
"Past medical history: ",
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
RadioListTile(
title: const Text("Yes"),
value: "yes",
groupValue: _medicalhistory,
onChanged: handleSelection,
),
if (_yes)
const TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter a search term',
),
),
RadioListTile(
title: const Text("No"),
value: "no",
groupValue: _medicalhistory,
onChanged: (value) {
setState(() {
_medicalhistory = value.toString();
});
},
),
],
)
],
),
),
Please see the code I have made. Please guide.
2
Answers
This is because you change the
_yes
value only in the Yes radio button, not in the No one. Also, you don’t update_medicalhistory
variable which is used to decide which radio is selected.You can modify your
_handleSelection
a little bit so that it covers both cases:And make this function also be used in the No radio. Also, to get advantage of strict typing, make your
RadioListTile
intoRadioListTile<String>
.That will make your code work like you want.
Furthermore, I can recommend other things to improve in your code:
_showPastMedicalHistory
instead of_yes
.You kind of misunderstood how RadioButtons work and what is groupValue. It just stores the state of the current selection, it’s not meant to get your TextField value. If the groupValue equals the the button’s assigned value it will appear as selected. You can have anything as a group value enums, lists etc.
I used a boolean since you only have two options. Also I changed how you display the textfield and added a controller, since you need one to get the value out of the textfield. Added a save button which assigns the current controller text to a variable.