从 Flutter 中的活动单选按钮获取文本值
Getting text value from active radio button in Flutter
您好,我的目标是拥有一个 RadioButton 列表,其中每个 RadioButton 都有其唯一的名称。在顶部有一个 Text() 字段,它将从单选按钮中获取该名称并将其相应地更新为单选按钮名称。
这是一个例子:
当您按下选项 2 单选按钮时,文本字段会随之更改:
我怎样才能做到这一点,因为我对 Flutter 和 Dart 还很陌生。提前致谢
代码:
class HomePage extends StatefulWidget {
const HomePage ({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<HomePage > createState() => _HomePage ();
}
class _HomePage extends State<HomePage > {
String _groupValue = '';
void checkRadio(String value ) {
setState(() {
_groupValue = value;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
),
body: SafeArea(
child: Center(
child: Column(
children: [
Container(height: 50,),
Text(_groupValue),
ListTile(
title: Text('Option1'),
leading: Radio(
value: 'Option1',
groupValue: _groupValue,
onChanged: (value) {
checkRadio(value as String);
}
),
),
ListTile(
title: Text('Option2'),
leading: Radio(
value: 'Option2',
groupValue: _groupValue,
onChanged: (value) {
checkRadio(value as String);
}
),
),
ListTile(
title: Text('Option3'),
leading: Radio(
value: 'Option3',
groupValue: _groupValue,
onChanged: (value) {
checkRadio(value as String);
}
),
),
ListTile(
title: Text('Option4'),
leading: Radio(
value: 'Option4',
groupValue: _groupValue,
onChanged: (value) {
checkRadio(value as String);
}
),
),
ListTile(
title: Text('Option5'),
leading: Radio(
value: 'Option5',
groupValue: _groupValue,
onChanged: (value) {
checkRadio(value as String);
}
),
),
],
),
)
),
);
}
}
结果: