Dropdown button menu item is not displaying after selecting the item. When users needed to select a single item from a list of the available items, but flutter is not displaying the selected item
class TaskTitleDiaglogscreen extends StatefulWidget {
const TaskTitleDiaglogscreen({
super.key, });
@override
State<TaskTitleDiaglogscreen> createState() => _TaskTitleDiaglogscreenState();
}
class _TaskTitleDiaglogscreenState extends State<TaskTitleDiaglogscreen> {
@override
Widget build(BuildContext context) {
final taskpriority = [
'Urgent',
'High priority',
'Important',
'Medium priority',
'Not important',
'Low priority',
];
String? selecteditem;
return AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
InputDecorator(
decoration: InputDecoration(
labelText: 'Select Priority',
labelStyle: TextStyle(fontSize: 20),
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(20.0)),
contentPadding: EdgeInsets.all(10),
),
child: ButtonTheme(
materialTapTargetSize: MaterialTapTargetSize.padded,
child: DropdownButton(
value: selecteditem,
isExpanded: true,
icon: Icon(Icons.keyboard_double_arrow_down_rounded),
items: taskpriority.map(buildMenuitem).toList(),
onChanged: (value) {
setState(() {
selecteditem = value;
});
print(selecteditem);
}),
),
)
],
),
);
}
DropdownMenuItem<String> buildMenuitem(String priority) => DropdownMenuItem(
value: priority,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(priority),
CircleAvatar(
radius: 10,
backgroundColor: _getColor(priority),
)
],
),
);
Color _getColor(String value) {
switch (value) {
case 'Urgent':
return Colors.red;
case 'High priority':
return Color.fromARGB(255, 243, 144, 144);
case 'Important':
return Colors.green;
case 'Medium priority':
return Colors.lightGreenAccent;
case 'Not important':
return Colors.blue;
case 'Low priority':
return Colors.lightBlueAccent;
default:
return Colors.black;
}
}
}
CodePudding user response:
You need to define variable outside the build method, else it will reassign the default value.
class _TaskTitleDiaglogscreenState extends State<TaskTitleDiaglogscreen> {
final taskpriority = [
'Urgent',
'High priority',
'Important',
'Medium priority',
'Not important',
'Low priority',
];
String? selecteditem;
@override
Widget build(BuildContext context) {