[Flutter]DropdownButtonの選択されたアイテムのウェジェットを設定するには?

Flutter

どうも、ちょげ(@chogetarou)です。

DropdownButtonの選択されたアイテムとして表示するウェジェットを設定する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

DropdownButtonの選択されたアイテムのウェジェットを設定するには、引数「selectedItemBuilder」を使います。

具体的には、DropdownButtonの引数「selectedItemBuilder」に関数を指定します。

指定した関数で、選択されたアイテムのウェジェットをリストで返します。

DropdownButton(
  selectedItemBuilder: (context) {
    return [
      /*選択されたアイテムのウェジェット*/
    ];
  },
  value: _text,
  items: [
    ・・・
  ],
  onChanged: (String? value) {
    ・・・
  },
  isDense: true,
),

引数「selectedItemBuilder」を使えば、DropdownButtonの選択されたアイテムとして表示するウェジェットの設定をすることが出来ます。

使用例

以下は、使用例です。

DropdownButton(
  selectedItemBuilder: (context) {
    return [
      Container(
        width: 100,
        child: Text('Hello'),
      ),
      Container(
        width: 100,
        child: Text('Hola'),
      ),
      Container(
        width: 100,
        child: Text('こんにちは'),
      ),
    ];
  },
  value: _text,
  items: [
    DropdownMenuItem(
      child: Text('Hello'),
      value: 'Hello',
    ),
    DropdownMenuItem(
      child: Text('Hola'),
      value: 'Hola',
    ),
    DropdownMenuItem(
      child: Text('こんにちは'),
      value: 'こんにちは',
    ),
  ],
  onChanged: (String? value) {
    setState(() {
      _text = value ?? 'Hello';
    });
  },
  isDense: true,
),

コメント

タイトルとURLをコピーしました