ChoiceChipとは
概要
ChoiceChip
は以下の様な選択式のボタンを作成するためのウィジェット。
公式のドキュメントは以下。
プロパティ
ChoiceChip
各プロパティの役割は以下の通り。
ChoiceChip( label: Text(ウィジェットに表示する文字列), selected: ウィジェットが選択される条件, backgroundColor: ウィジェットの背景色, selectedColor: 選択された際のウィジェットの背景色, onSelected: 選択された際のイベントハンドラ, ),
label
:ボタンの中央に表示する文字列を指定selected
:bool
型の値を渡す。この値がtrue
になると選択されたと認識されるbackgroundColor
:背景色selectedColor
:selected
がtrue
になっているときの背景色onSelected
:ウィジェットをタップされた際の挙動を指定。引数にはウィジェットが選択された際にtrue
が渡される
実装例
ChoiceChip
を用いて選択したボタンが白でハイライトされるアプリを作成する。
動作画像
サンプルアプリの動作は以下の通り。
ソースコード
このサンプルアプリのコードは以下。
Wrap( spacing: 10, children: [ ChoiceChip( label: Text("choice 0"), selected: _choiceIndex == 0, backgroundColor: Colors.grey[600], selectedColor: Colors.white, onSelected: (_) { setState(() { _choiceIndex = 0; }); }, ), ChoiceChip( label: Text("choice 1"), selected: _choiceIndex == 1, backgroundColor: Colors.grey[600], selectedColor: Colors.white, onSelected: (_) { setState(() { _choiceIndex = 1; }); }, ), ChoiceChip( label: Text("choice 2"), selected: _choiceIndex == 2, backgroundColor: Colors.grey[600], selectedColor: Colors.white, onSelected: (_) { setState(() { _choiceIndex = 2; }); }, ), ChoiceChip( label: Text("choice 3"), selected: _choiceIndex == 3, backgroundColor: Colors.grey[600], selectedColor: Colors.white, onSelected: (_) { setState(() { _choiceIndex = 3; }); }, ), ], )
解説
実装例では選択されているボタンのインデックスを_choiceIndex
で管理している。
そしてボタンのどれかがタップされた際、setState
で_choiceIndex
を新たに選択されたアイテムのインデックスに変更している。
またデザイン面でも一工夫している。
未選択ボタンと見分けがつくようにbackgroundColor
をColors.white
に指定し、選択されたボタンのみが白でハイライトされるように目立たせている。
ChoiceChipのレイアウトはWrapで指定している。ChoiceChipはWrapで配置されるUIをよく見るので今回使用した。 Wrapウィジェットの使用方法は以下を参照してほしい。