Radio 元件 (Widget) 全新設計
了解 Flutter 3.35 中 radio 元件的變更內容。
摘要
#
引入了 RadioGroup 元件 (Widget),用於集中管理 groupValue,以及一組 Radio 元件的 onChanged
回呼 (callback)。因此,個別的 Radio.groupValue 和 Radio.onChanged 屬性已被棄用。
背景
#
為了符合 APG(ARIA Practices Guide)對於 radio 按鈕群組在鍵盤導覽和語意屬性的要求,Flutter 需要一個專用的 radio 群組概念。引入包裹元件 RadioGroup,即可直接支援這些功能。這項變更同時也讓個別
Radio 元件的 API 得以簡化。
變更說明
#以下 API 已被棄用:
Radio.onChangedRadio.groupValueCupertinoRadio.onChangedCupertinoRadio.groupValueRadioListTile.groupValueRadioListTile.onChanged。
遷移指南
#如果你正在使用這些屬性,可以使用 RadioGroup 來重構你的程式碼。
案例 1:簡單案例
#遷移前的程式碼:
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Radio<int>(
value: 0,
groupValue: _groupValue,
onChanged: (int? value) {
setState(() {
_groupValue = value;
});
},
),
Radio<int>(
value: 2,
groupValue: _groupValue,
onChanged: (int? value) {
setState(() {
_groupValue = value;
});
},
),
],
);
}
遷移後的程式碼:
Widget build(BuildContext context) {
return RadioGroup<int>(
groupValue: _groupValue,
onChanged: (int? value) {
setState(() {
_groupValue = value;
});
},
child: Column(
children: <Widget>[
Radio<int>(value: 0),
Radio<int>(value: 2),
],
),
);
}
案例 2:disabled radio
#遷移前的程式碼:
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Radio<int>(
value: 0,
groupValue: _groupValue,
onChanged: (int? value) {
setState(() {
_groupValue = value;
});
},
),
Radio<int>(
value: 2,
groupValue: _groupValue,
onChanged: null, // disabled
),
],
);
}
遷移後的程式碼:
Widget build(BuildContext context) {
return RadioGroup<int>(
groupValue: _groupValue,
onChanged: (int? value) {
setState(() {
_groupValue = value;
});
},
child: Column(
children: <Widget>[
Radio<int>(value: 0),
Radio<int>(value: 2, enabled: false),
],
),
);
}
案例 3:混合群組或多重選擇
#遷移前的程式碼:
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Radio<int>(
value: 1,
groupValue: _groupValue,
onChanged: (int? value) {
setState(() {
_groupValue = value;
});
}, // disabled
),
Radio<String>(
value: 'a',
groupValue: _stringValue,
onChanged: (String? value) {
setState(() {
_stringValue = value;
});
},
),
Radio<String>(
value: 'b',
groupValue: _stringValue,
onChanged: (String? value) {
setState(() {
_stringValue = value;
});
},
),
Radio<int>(
value: 2,
groupValue: _groupValue,
onChanged: (int? value) {
setState(() {
_groupValue = value;
});
}, // disabled
),
],
);
}
遷移後的程式碼:
Widget build(BuildContext context) {
return RadioGroup<int>(
groupValue: _groupValue,
onChanged: (int? value) {
setState(() {
_groupValue = value;
});
},
child: Column(
children: <Widget>[
Radio<int>(value: 1),
RadioGroup<String>(
child: Column(
children: <Widget>[
Radio<String>(value: 'a'),
Radio<String>(value: 'b'),
]
),
),
Radio<int>(value: 2),
],
),
);
}
時程
#
合併於版本:3.34.0-0.0.pre
穩定版發佈於:3.35
參考資料
#API 文件:
相關議題:
相關 PR:
Unless stated otherwise, the documentation on this site reflects Flutter 3.44.0. Page last updated on 2026-06-14. View source or report an issue.