Adding icon to left of DropDownButton (expanded) in flutter
Solution 1
There is no specific attribute for adding icon the way you want but you can always work around your code and find some tweaks. Use the following code which will place you Icon()
on top of your DropDownButton()
button.
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey,
blurRadius: 20.0,
spreadRadius: 0.5,
offset: Offset(1.0, 1.0),
),
],
),
padding: EdgeInsets.only(left: 44.0),
margin: EdgeInsets.only(top: 64.0, left: 16.0, right: 16.0),
child: DropdownButton(
isExpanded: true,
items: your_list.map(
(val) {
return DropdownMenuItem(
value: val,
child: Text(val),
);
},
).toList(),
value: _currentSelectedItem,
onChanged: (value) {
setState(() {
_currentSelectedItem = value;
});
},
),
),
Container(
margin: EdgeInsets.only(top: 80.0, left: 28.0),
child: Icon(
Icons.person,
color: Colors.redAccent,
size: 20.0,
),
),
],
),
);
}
Solution 2
Use DropdownButtonFormField as it has decoration property. You can use prefixIcon attribute to set icon on left side.
Example:
DropdownButtonFormField<String>(
decoration: InputDecoration(
prefixIcon: Icon(Icons.person),
),
hint: Text('Please choose account type'),
items: <String>['A', 'B', 'C', 'D'].map((String value) {
return DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
onChanged: (_) {},
),
Result:
Muhammad Faizan
Have strong experience in coding confusable bugs xD
Updated on September 01, 2021Comments
-
Muhammad Faizan over 2 years
I want to add icon to left of
DropDownButton
but can't find a way to do so. What I want to achieve is like this:I have tried following code but it places icon to right where I don't want it and it also overrides arrow icon:
`@override Widget build(BuildContext context) { return Scaffold( body: Container( margin: EdgeInsets.only(top: 64.0, left: 16.0, right: 16.0), color: Colors.white, child: DropdownButton( icon: Icon( Icons.person, color: Colors.redAccent, size: 20.09, ), isExpanded: true, items: _studentList.map((val) { return DropdownMenuItem( value: val, child: Text(val), ); }).toList(), value: _currentSelectedItem, onChanged: (value) { setState(() { _currentSelectedItem = value; }); }, ), ), ); }`
Output of above code is like this:
I have also tried to place
Icon()
andDropDownButton()
insideRow()
widget but that does not allow theDropDownButton()
to expand to full width.Any help would be appreciated.
Thanks