すらぼうの開発ノート

モバイルアプリエンジニアのメモ

【Flutter】ChoiceChipで選択式のボタンを作成する

ChoiceChipとは

概要

ChoiceChipは以下の様な選択式のボタンを作成するためのウィジェット

youtubeの選択式ボタン

公式のドキュメントは以下。

api.flutter.dev

プロパティ

ChoiceChip各プロパティの役割は以下の通り。

ChoiceChip(
  label: Text(ウィジェットに表示する文字列),
  selected: ウィジェットが選択される条件,
  backgroundColor: ウィジェットの背景色,
  selectedColor: 選択された際のウィジェットの背景色,
  onSelected: 選択された際のイベントハンドラ,
),
  • label:ボタンの中央に表示する文字列を指定
  • selectedbool型の値を渡す。この値がtrueになると選択されたと認識される
  • backgroundColor:背景色
  • selectedColorselectedtrueになっているときの背景色
  • onSelectedウィジェットをタップされた際の挙動を指定。引数にはウィジェットが選択された際にtrueが渡される

実装例

ChoiceChipを用いて選択したボタンが白でハイライトされるアプリを作成する。

動作画像

サンプルアプリの動作は以下の通り。

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を新たに選択されたアイテムのインデックスに変更している。

またデザイン面でも一工夫している。 未選択ボタンと見分けがつくようにbackgroundColorColors.whiteに指定し、選択されたボタンのみが白でハイライトされるように目立たせている。

ChoiceChipのレイアウトはWrapで指定している。ChoiceChipはWrapで配置されるUIをよく見るので今回使用した。 Wrapウィジェットの使用方法は以下を参照してほしい。

note-tmk.hatenablog.com