How should I customize DropdownButtons and DropdownMenuItems in Flutter?
You can accomplish this by wrapping the DropdownButton
in a Theme
widget and overriding the canvasColor
.
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
State createState() => new MyHomePageState();
}
class MyHomePageState extends State<MyHomePage> {
int _value = 42;
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new Theme(
data: Theme.of(context).copyWith(
canvasColor: Colors.blue.shade200,
),
child: new DropdownButton(
value: _value,
items: <DropdownMenuItem<int>>[
new DropdownMenuItem(
child: new Text('Foo'),
value: 0,
),
new DropdownMenuItem(
child: new Text('Bar'),
value: 42,
),
],
onChanged: (int value) {
setState(() {
_value = value;
});
},
),
),
),
);
}
}
I was able to change the background for the Dropdown by wrapping it in a Container
with the color
property set.
Before:
After:
Here's the code:
Define these values in the widget state:
final items = ['One', 'Two', 'Three', 'Four'];
String selectedValue = 'Four';
then use this code
Container(
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: Colors.white, borderRadius: BorderRadius.circular(10)),
// dropdown below..
child: DropdownButton<String>(
value: selectedValue,
onChanged: (String newValue) =>
setState(() => selectedValue = newValue),
items: items
.map<DropdownMenuItem<String>>(
(String value) => DropdownMenuItem<String>(
value: value,
child: Text(value),
))
.toList(),
// add extra sugar..
icon: Icon(Icons.arrow_drop_down),
iconSize: 42,
underline: SizedBox(),
),
);