DropdownButtonを使うときに、選択されたテキストのスタイルをドロップダウンが開いた状態と閉じた状態とで変えたい場合、selectedItemBuilder
とitems
を使い分けると実現できます。
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(),
),
),
);
}
}
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);
}