どうも、ちょげ(@chogetarou)です。
リストビューでラジオボタンを実装する方法を紹介します。
方法
リストビューでラジオボタンを実装するには、RadioListTileウェジェットを使います。
まず、選択された値を格納する変数を用意します。
var _selectedIndex = -1;
次に、リストビューのchildrenに「RadioListTile」を配置します。
この時、引数「value」には選択された時に変数に格納したい値、引数「groupValue」には用意した変数を指定します。
また、引数「title」には、テキストを指定します。
ListView(
children: [
RadioListTile(
value: /*選択された時に取得したい値*/,
groupValue: _selectdIndex
title: /*テキスト*/,
),
],
),
そして、引数「onChanged」にラジオボタンが押された時に値を切り替える処理を追加します。
ListView(
children: [
RadioListTile(
value: /*選択された時に取得したい値*/,
groupValue: _selectedIndex,
title: /*テキスト*/,
),
onChanged: (int? value) {
setState(() {
_selectedIndex = value!;
});
},
],
),
切り替える処理では、用意した変数に選択された値が格納されるようにします。
最後に、RadioListTileを必要なだけ用意すれば、リストビューでラジオボタンを実装できます。
以下は、使用例です。
var _selectedIndex = -1;
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: ListView(
children: [
RadioListTile(
value: 1,
groupValue: _selectedIndex,
title: Text('Item1'),
onChanged: (int? value) {
setState(() {
_selectedIndex = value!;
});
},
),
RadioListTile(
value: 2,
groupValue: _selectedIndex,
title: Text('Item2'),
onChanged: (int? value) {
setState(() {
_selectedIndex = value!;
});
},
),
RadioListTile(
value: 3,
groupValue: _selectedIndex,
title: Text('Item3'),
onChanged: (int? value) {
setState(() {
_selectedIndex = value!;
});
},
),
RadioListTile(
value: 4,
groupValue: _selectedIndex,
title: Text('Item4'),
onChanged: (int? value) {
setState(() {
_selectedIndex = value!;
});
},
),
RadioListTile(
value: 5,
groupValue: _selectedIndex,
title: Text('Item5'),
onChanged: (int? value) {
setState(() {
_selectedIndex = value!;
});
},
),
],
),
),
);
}
コメント