我正在尝试创建一个包含3个单选按钮的性别选择功能。我已经完成了这段代码,但是它并没有按照我的要求工作。
单选按钮容器
final _radio_colume_container = Container(
margin: const EdgeInsets.fromLTRB(50, 15, 50, 00),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Gender*',
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
add_radio_button(0, 'Male'),
add_radio_button(1, 'Female'),
add_radio_button(2, 'Others'),
],
),
],
),
);
add_radio_button方法
Row add_radio_button(int btnValue, String title) {
return Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Radio(
activeColor: Colors.green,
value: btnValue,
groupValue: -1,
onChanged: _handleradiobutton,
),
Text(title)
],
);
}
我正在实现这一目标
我想实现这一目标。
请帮助!!!
答案 0 :(得分:2)
List gender=["Male","Female","Other"];
String select;
Row addRadioButton(int btnValue, String title) {
return Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Radio(
activeColor: Theme.of(context).primaryColor,
value: gender[btnValue],
groupValue: select,
onChanged: (value){
setState(() {
print(value);
select=value;
});
},
),
Text(title)
],
);
}
//Use the above widget where you want the radio button
child: Row(
children: <Widget>[
addRadioButton(0, 'Male'),
addRadioButton(1, 'Female'),
addRadioButton(2, 'Others'),
],
),
答案 1 :(得分:1)
您应该查看RadioListTile
,因为它提供了dense
属性,这将有助于减少按钮与其标题之间的填充。
答案 2 :(得分:0)
在@Shubham的答案中应用了一些重构之后,给出了通用的代码版本以用于多种目的。
import 'package:flutter/material.dart';
/// Requires a list of string ['Male','Female','Other'] only once.
class GenderField extends StatelessWidget {
final List<String> genderList;
GenderField(this.genderList);
@override
Widget build(BuildContext context) {
String select;
Map<int, String> mappedGender = genderList.asMap();
return StatefulBuilder(
builder: (_, StateSetter setState) => Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Gender : ',
style: TextStyle(fontWeight: FontWeight.w400),
),
...mappedGender.entries.map(
(MapEntry<int, String> mapEntry) => Row(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Radio(
activeColor: Theme.of(context).primaryColor,
groupValue: select,
value: genderList[mapEntry.key],
onChanged: (value) => setState(() => select = value),
),
Text(mapEntry.value)
]),
),
],
),
);
}
}
在main.dart中,此小部件可以称为
// Some code
Padding(
padding: EdgeInsets.only(bottom: 10),
child: GenderField(['Male','Female','Other'])
)