13
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Flutter #2Advent Calendar 2019

Day 14

DropdownButtonで選択されたテキストのスタイルをドロップダウンの開閉によって変える

Posted at

DropdownButtonを使うときに、選択されたテキストのスタイルをドロップダウンが開いた状態と閉じた状態とで変えたい場合、selectedItemBuilderitemsを使い分けると実現できます。

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final String text = "Flutter";
  
  List<String> _items = ["A", "B", "C"];
  String _selectedItem = "A";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: DropdownButton<String>(
          value: _selectedItem,
          onChanged: (String newValue) {
            setState(() {
              _selectedItem = newValue;
            });
          },
          selectedItemBuilder: (context) {
            return _items.map((String item) {
              return Text(
                item,
                style: TextStyle(color: Colors.pink),
              );
            }).toList();
          },
          items: _items.map((String item) {
            return DropdownMenuItem(
              value: item,
              child: Text(
                item,
                style: item == _selectedItem
                    ? TextStyle(fontWeight: FontWeight.bold)
                    : TextStyle(fontWeight: FontWeight.normal),
              ),
            );
          }).toList(),
        ),
      ),
    );
  }
}

selectedItemBuilder
image.png

items
image.png

dropdown.dartを見ると、enabledでselectedItemBuilderがnullの場合はList<Widget>.from(widget.items)が使われることがわかります。

[flutter/lib/src/material/dropdown.dart#L1257]
// The width of the button and the menu are defined by the widest
// item and the width of the hint.
List<Widget> items;
if (_enabled) {
  items = widget.selectedItemBuilder == null
    ? List<Widget>.from(widget.items)
    : widget.selectedItemBuilder(context);
} else {
  items = widget.selectedItemBuilder == null
    ? <Widget>[]
    : widget.selectedItemBuilder(context);
}

13
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?