[Flutter]ドロップダウンボタンにラベルを表示するには?

Flutter

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

ドロップダウンボタンにラベルを表示する方法を紹介します。

スポンサーリンク

方法

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

ドロップダウンボタンにラベルを表示するには、DropdownButtonFormFieldを使います。

まず、DropdownButtonを使っているならば、DropdownButtonFormFieldに置き換えます。

次に、DropdownButtonFormFieldの引数「decoration」にInputDecorationを指定します。

そして、InputDecorationの引数「label」にラベルとなる文字列を指定します。

DropdownButtonFormField(
  decoration: InputDecoration(
    labelText: 'ラベル',
  ),
  value: _text,
  items: [
    ・・・
  ],
  onChanged: (String? value) {
    ・・・
  },
),

DropdownButtonFormFieldを使えば、ドロップダウンボタンにラベルを表示することが出来ます。

使用例

以下は、使用例です。

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var _text = 'Hello';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: DropdownButtonFormField(
            decoration: InputDecoration(
              labelText: 'ラベル',
            ),
            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';
              });
            },
          ),
        ),
      ),
    );
  }
}

コメント

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