1 min readDec 25, 2020
What you can do is remove the _selectedItem initiate in init state and then add a Text()
hint for the DropdownButton
Widget as follows. For any help please send me a mail to yashodgayashan@gmail.com.
import 'package:flutter/material.dart';class DropDownButton extends StatefulWidget {
@override
_DropDownButtonState createState() => _DropDownButtonState();
}class _DropDownButtonState extends State<DropDownButton> {
List<ListItem> _dropdownItems = [
ListItem(1, "First Value"),
ListItem(2, "Second Item"),
ListItem(3, "Third Item"),
ListItem(4, "Fourth Item")
];
List<DropdownMenuItem<ListItem>> _dropdownMenuItems;
ListItem _selectedItem;
void initState() {
super.initState();
_dropdownMenuItems = buildDropDownMenuItems(_dropdownItems);
} List<DropdownMenuItem<ListItem>> buildDropDownMenuItems(List listItems) {
List<DropdownMenuItem<ListItem>> items = List();
for (ListItem listItem in listItems) {
items.add(
DropdownMenuItem(
child: Text(listItem.name),
value: listItem,
),
);
}
return items;
}@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter tutorial"),
),
body: Column(
children: <Widget>[
Row(
children: <Widget>[
Container(
padding: EdgeInsets.all(10.0),
child: Text(
"Dropdown",
style: TextStyle(fontSize: 16.0),
),
),
Container(
padding: EdgeInsets.all(20.0),
child: DropdownButton<ListItem>(
hint: Text("Select One"),
value: _selectedItem,
items: _dropdownMenuItems,
onChanged: (value) {
setState(() {
_selectedItem = value;
});
}
),
),
],
),
],
),
);
}
}class ListItem {
int value;
String name;
ListItem(this.value, this.name);
}