[Flutter]DropdownButtonの値が変更された時に処理をするには?

Flutter

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

DropdownButtonの値が変更された時に処理をする方法を紹介します。

スポンサーリンク

方法

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

DropdownButtonの値が変更された時に処理をするには、引数「onChanged」を使います。

具体的には、引数「onChanged」に値の変更で呼び出す関数を指定します。

呼び出す関数は、「(value){}」のようなものです。

DropdownButton(
  value: _text,
  items: [
    ・・・・
  ],
  onChanged: (value) {
    //値が変更された時の処理
  },
),

変更された時の処理自体は、関数の{}内に指定します。

引数「onChanged」を使えば、DropdownButtonの値が変更された時に処理をすることが出来ます。

使用例

以下は、使用例です。

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: SizedBox(
          width: 200,
          child: DropdownButton(
            isExpanded: true,
            items: [
              DropdownMenuItem(
                child: Text('Hello'),
                value: 'Hello',
              ),
              DropdownMenuItem(
                child: Text('Hola'),
                value: 'Hola',
              ),
              DropdownMenuItem(
                child: Text('こんにちは'),
                value: 'こんにちは',
              ),
            ],
            onChanged: (String? value) {
              setState(() {
                _text = value ?? 'Hello';
              });
            },
            value: _text,
          ),
        ),
      ),
    );
  }
}

コメント

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