ふらっとFlutter

Flutterでのアプリ開発についてメモしていきます

FlutterでChoiceChipを使って選択肢を表示する

Materialパッケージに含まれるChoiceChipでは選択肢の表示とその選択を実現できます。
実装する機会があったのでコードをメモしておきます。

ChoiceChipの実装

このような選択肢からひとつを選択できるものを作ります。

// 選択肢の準備
var _visitOptions = ["すべて", "訪問済", "未訪問"];
var _selectedVisitIndex = 0;

_visitOptions.indexedMap((index, title) {
      choices.add(Container(
        padding: const EdgeInsets.all(8.0),
        child: ChoiceChip(
          selectedColor: Colors.green[600],
          backgroundColor: Colors.grey[300],
          label: Text(title),
          selected: _selectedVisitIndex == index,
          onSelected: (_) {
            // 選択された時の処理
            print("title is " + title + ", index is " + index.toString());
          },
        ),
      ));
    });

...

// indexと項目の両方を使いたいのでExtensionを定義
extension IndexedMap<T, E> on List<T> {
  List<E> indexedMap<E>(E Function(int index, T item) function) {
    final list = <E>[];
    asMap().forEach((index, element) {
      list.add(function(index, element));
    });
    return list;
  }
}

デザインを整えるための項目も多いですが、コアとなるのは以下の部分です。

ChoiceChip(
  selectedColor: Colors.green[600],
  backgroundColor: Colors.grey[300],
  label: Text(title),
  selected: _selectedVisitIndex == index,
  onSelected: (_) {
    // 選択された時の処理
    print("title is " + title + ", index is " + index.toString());
    _selectedVisitIndex = index;
  },
)

onSelected で選択された時の処理を実装し、 selected でその項目の選択状態を返します。 そのほかにも設定できる項目が色々あってデザインのカスタマイズの幅も広いです。

また、IndexedMapの実装はこちらの記事を参考にさせていただきました。

qiita.com

まとめ

ChoiceChipの実装方法を書きました。 FlutterのMaterialのコンポーネントで選択肢を選ばせるというと SimpleDialog もありますが、今回のように選択肢の数が少ない場合は並べて表示する方が親切ではないかと思っています。