How to get DropdownMenuItem from a list - flutter

I have tried to use a function and for in loop to loop through a list and then create dropdownMenuItems. I am getting this error 'There should be exactly one item with [DropdownButton]'s value Either zero or 2 or more [DropdownMenuItem]s were detected with the same value'. I have look through similar solutions stating that the default value should be one of the values of the list which is not my case
Below is the list
const List<String> currenciesList = [
'AUD',
'BRL',
'CAD',
'CNY',
'EUR',
'GBP',
'HKD',
'IDR',
'ILS',
'INR',
'JPY',
'MXN',
'NOK',
'NZD',
'PLN',
'RON',
'RUB',
'SEK',
'SGD',
'USD',
'ZAR'
];
and the loop
String selectedCurrency = 'USD';
List<DropdownMenuItem<String>> dropdownItems = [];
List<DropdownMenuItem<String>> getDropDownItems() {
for (String currency in currenciesList) {
var newItem = DropdownMenuItem(
child: Text(currency),
value: currency,
);
dropdownItems.add(newItem);
}
return dropdownItems;
}
lastly the dropdownbutton
child: DropdownButton<String>(
value: selectedCurrency,
items: getDropDownItems(),
onChanged: (value) {
setState(() {
selectedCurrency = value!;
});
},
Please help me understand what i must have done wrong

Your code-snippet
DropdownButton<String>(
value: selectedCurrency,
items: getDropDownItems(), ///<= adding items on every state-build
onChanged: (value) {
setState(() {
selectedCurrency = value!;
});
},
On state changes means after you click on DropdownMenuItem you are calling again getDropDownItems(), in this case our it will add DropdownMenuItem again to dropdownItems, and so the DropdownButton having duplicate values, and you are getting errors.
Use initState to call it once, or just initialize the dropdownMenuItem.
Here is the Solution Widget
class _ItemSectionState extends State<ItemSection> {
List<DropdownMenuItem<String>> dropdownItems = []; //* you can make nullable if you want, I'm doing it to force having String.
String selectedCurrency = 'USD';
#override
void initState() {
super.initState();
dropdownItems = List.generate(
currenciesList.length,
(index) => DropdownMenuItem(
value: currenciesList[index],
child: Text(
currenciesList[index],
),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
DropdownButton<String>(
items: dropdownItems,
value: selectedCurrency,
onChanged: (value) {
setState(() {
selectedCurrency = value!;
});
},
),
],
),
);
}
}

The error occurs due to duplicate values..
When you try to change the value of the drop down, the getDropDownItems function is rerun and the logic in there just duplicates the values for the dropdown.
a quick fix would be to simply map over the currenciesList as opposed to writing a function to add the widgets to a List as shown below:
String selectedCurrency = 'USD';
...
child: DropdownButton<String>(
value: selectedCurrency,
items: currenciesList.map((currency) => DropdownMenuItem(
child: Text(currency),
value: currency,
),
),
onChanged: (value) {
setState(() {
selectedCurrency = value!;
});
},
...

Related

How to Create a Single Selected Dropdown List in Flutter?

I am a flutter beginner. How to Create a Single Selected Dropdown List in Flutter?
Like This.
I tried, but I didn't get what I wanted.
String dropdownvalue = 'Bahrain';
Container(
width: 308,
child: DropdownButton(
// Initial Value
value: dropdownvalue,
// Down Arrow Icon
icon: const Icon(Icons.keyboard_arrow_down),
// Array list of items
items: dropdownvalue.map((String dropdownvalue) {
return DropdownMenuItem(
value: dropdownvalue,
child: Text(dropdownvalue),
);
}).toList(),
// After selecting the desired option,it will
// change button value to selected value
onChanged: (String? newValue) {
setState(() {
dropdownvalue = newValue!;
});
},
),
),
You should have list of items and selectedItem to manage the list and selection state.
class _YourState extends State<MyHomePage> {
List<String> countries = [
'Bahrain',
'India',
'Iraq',
'America',
];
String? dropdownvalue ;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: DropdownButton(
// Initial Value
value: dropdownvalue,
icon: const Icon(Icons.keyboard_arrow_down),
isExpanded: true,
items: countries.map((String dropdownvalue) {
return DropdownMenuItem(
value: dropdownvalue,
child: Text(dropdownvalue),
);
}).toList(),
hint: Text('Country'),
onChanged: (String? newValue) {
setState(() {
dropdownvalue = newValue!;
});
},
),
),
);
}
}

Flutter DropdownButton returns error for onChange event

I'm writing a project and wants to add a DropDownButton but it always return error once I add onCnange event. Dropdown always returns error. I don't know what's wrong with it.
#override
Widget build(BuildContext context) {
return Material( child: Column( children: [
DropdownButton(items: [], value: dropdownValue, onChanged: (String value) {
setState(() {
dropdownValue = value;
});
},)
], ), );
}
Error message
The argument type 'void Function(String)' can't be assigned to the parameter type 'void Function(Object?)?'.
function and value might be nullable, so either remove String type from the callback or use the nullable type.
Solution 1
DropdownButton<String>(
items: [],
value: dropdownValue,
onChanged: (value) {
setState(() {
dropdownValue = value;
});
},
)
Solution 2
DropdownButton<String>(
items: [],
value: dropdownValue,
onChanged: (String? value) {
setState(() {
dropdownValue = value;
});
},
)

Flutter/Dart: Reuse widget multiple times and return setState value

I'm using a DropdownButton widget many times on one page in my app. In order to prevent rewriting of code, I'd like to use the widget once and pass values to it. The issue I'm having is that I need to setState the "value", which cannot occur when passing an argument to the mentioned method. How does one go about reusing a widget structure, and have it setState for multiple different values? My example below:
String trial;
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Column(
children: [
//TRIAL
dropDownLists(
hint: "Trial",
items: ["1", "2", "3", "4"],
value: trial, //<---This value does not update when option chosen
),
],
),
),
);
}
//Method
Widget dropDownLists({String hint, List<String> items, String value}) {
print(value); //<--- null, but giving a value throws errors because a value
//doesn't match an item on the list
return DropdownButton<String>(
hint: Text(hint),
value: value,
onChanged: (selectedValue) {
print(selectedValue);
print(value);
setState(() {
value = selectedValue;
});
},
items: items.map((String selection) {
return DropdownMenuItem<String>(
value: selection,
child: Text(selection),
);
}).toList(),
);
}
Issue: DropdownList works up until a value needs to be selected. Once a value is selected, it is not shown as being chosen
Theory: I currently am not returning the value properly, but don't know how to.
you can do it like this:
String trial;
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Column(
children: [
dropDownLists(
hint: "Trial",
items: ["1", "2", "3", "4"],
value: trial,
onChange: (value) => setState(() => trial = value),
),
],
),
),
);
}
Widget dropDownLists({
String hint,
List<String> items,
String value,
Function(String) onChange,
}) {
print(value);
return DropdownButton<String>(
hint: Text(hint),
value: value,
onChanged: onChange,
items: items.map((String selection) {
return DropdownMenuItem<String>(
value: selection,
child: Text(selection),
);
}).toList(),
);
}

Cannot Select Checkbox List Tile Flutter

I've created a map of values to make checkboxes. The map consists of String and bools and when the value of the bool is changed, the check box value should change.
EDIT 1:
My ListView Checkbox
CheckboxListTile(
title: new Text(
key,
style: textHeaderStyle,
),
value: _selectedOrders.contains(undeliveryOrders[key]),
activeColor: Colors.pink,
checkColor: Colors.white,
onChanged: (bool value) {
setState(() {
if(value){
_selectedOrders.add(undeliveryOrders[key]);
undeliveryOrders[key] = value;
}else{
setState(() {
_selectedOrders.remove(undeliveryOrders[key]);
});
}
});
},
)
Creating the Map:
void _formatOrders(availableOrders) {
for (int i = 0; i < availableOrders.length; i++) {
var tempOrder = '${availableOrders[i].customer.uniqueInfo.name} , ${availableOrders[i].address}';
undeliveryOrders['$tempOrder'] = false;
}
print('$undeliveryOrders');
print('$numbers');
}
Selected Order Method
var _selectedOrders = [];
getItems() {
undeliveryOrders.forEach((key, value) {
if (value == false) {
_selectedOrders.add(key);
}
});
print(_selectedOrders);
_selectedOrders.clear();
}
I think you might be over complicating things every value does not have to be mapped to a boolean the way I do it is I add the value that gets checked to an array then check if that item is in that array if it is its true if not its false. You just have to remember to remove the item if the checkbox is unchecked here is some sample code for you.
List<String> items = ['Item 1', 'Item 2', 'Item 3'];
List<String> isChecked = [];
//Initialized outside build
ListView(
children: <Widget>[
...items
.map(
(item) => CheckboxListTile(
subtitle: Text('This is a subtitle'),
secondary: Text('This is Secondary text'),
title: Text(item),
value: isChecked.contains(item),
onChanged: (bool value) {
if (value) {
setState(() {
isChecked.add(item);
});
} else {
setState(() {
isChecked.remove(item);
});
}
},
),
)
.toList()
],
),
In my case, the setState() is not responding, try to use StatefulBuilder().
For Example:
...
bool isSelected = false;
StatefulBuilder(
builder: (context, _setState) {
return ListView(
children: [
CheckboxListTile(
value: isSelected,
onChanged: (bool? value) {
_setState(() => isSelected = value);
},
),
],
);
},
);
...
You can try with this code bellow ?
onChanged: (bool value) {
setState(() {
undeliveryOrders[key] = value ?? false;
});
},

Error: Either zero or 2 or more [DropdownMenuItem]s were detected with the same value I/flutter (18363): 'package:flutter/src/material/dropdown.dart':

Error code
Hi I'm new to flutter and have a question about dropdownbutton regarding using the same values for multiple dropdownbutton.
From my understanding from the error, it was due to using the same list for 2 or more dropdownbuttons in the same activity.
How am i able to resolve this error but still able to reuse the list for 2 or more dropdownbuttons?
String _value1;
String _value2;
final List<String> nameList = <String>[
"Name1",
"Name2",
"Name3",
"Name4",
"Name5",
"Name6",
"Name7",
"Name8"
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 2.0,
title: Text('Hello'),
),
body: ListView(
children: <Widget>[
Row(
children: <Widget>[
Text('Name: '),
Center(
child: DropdownButton(
value: _value1,
onChanged: (value) {
setState(() {
_value1 = value;
});
},
items: nameList.map(
(item) {
return DropdownMenuItem(
value: item,
child: new Text(item),
);
},
).toList(),
),
),
],
),
Row(
children: <Widget>[
Text('Name: '),
Center(
child: DropdownButton(
value: _value2,
onChanged: (value) {
setState(() {
_value2 = value;
});
},
items: nameList.map(
(item) {
return DropdownMenuItem(
value: item,
child: new Text(item),
);
},
).toList(),
),
),
],
),
],
),
backgroundColor: Colors.grey[200],
);
}
}
I had the exact same error, multiple Dropdowns all feeding from the same static list, the only difference is that in my case, it was a list of Objects, not Strings.
So, if it's a static list, there's no way it's empty, no duplicate values in the list, AND you already make sure value is not empty? Then the only option remaining is that item.value is different than value
In my case, as it was an Object list, I had to overwrite operator == and hashcode methods in my Object class.
bool operator ==(dynamic other) =>
other != null && other is TimeSelection && this.hour == other.hour;
#override
int get hashCode => super.hashCode;
And that was it. I didn't had to initialize _value1 or _value2
You are getting that exception because _value1 and _value2 aren't initialized and providing empty to the dropdown widget.
You could do something like this:
DropdownButton(
value: _value1.isNotEmpty ? _value1 : null, // guard it with null if empty
items: nameList.map((item) {
return DropdownMenuItem(
value: item,
child: new Text(item),
);
}).toList(),
);
This exception you have because of mistakes:
No _value1 and _value2 initialization.
When you initialize them make sure that _value1 and _value2 right from nameList e.g.
_value1 = nameList[0];
_value2 = nameList[3];
this is important step with complex data type, but in your case
_value1 = "Name1";
_value2 = "Name4";
will be sufficient.
Full example:
String _value1;
String _value2;
final List<String> nameList = <String>[
"Name1",
"Name2",
"Name3",
"Name4",
"Name5",
"Name6",
"Name7",
"Name8"
];
/// initialization is here:
#override
void initState() {
super.initState();
_value1 = nameList[0];
_value2 = nameList[3];
}
#override
Widget build(BuildContext context) {
return ListView(
children: <Widget>[
Row(
children: <Widget>[
Text('Name: '),
Center(
child: DropdownButton(
value: _value1,
onChanged: (value) {
setState(() {
_value1 = value;
});
},
items: nameList.map(
(item) {
return DropdownMenuItem(
value: item,
child: new Text(item),
);
},
).toList(),
),
),
],
),
Row(
children: <Widget>[
Text('Name: '),
Center(
child: DropdownButton(
value: _value2,
onChanged: (value) {
setState(() {
_value2 = value;
});
},
items: nameList.map(
(item) {
return DropdownMenuItem(
value: item,
child: new Text(item),
);
},
).toList(),
),
),
],
),
],
);
}
}
I have the same problem, and I solved it.
The dropdown button needs items list and value. We define items and selected items, but the item chosen instance does not inside the items list.
You should try this and fix your logic.
(value ıs selected item value for user)
var _value = itemList.isEmpty
? value
: itemList.firstWhere((item) => item.value == value.value);
More : https://gist.github.com/VB10/fd560694fec0a38751e798a213408001
You must initialise the _value1 and _value2 and make sure those values are also present in nameList.
My solution was more simple than every one else. The fact that was find a value that wasn't the same as in the list, is because I have put a value in the variable, that wasn't either full or empty, the value was this ("") and it has to be null for the Dropdown value instance. So, I just have put a value null in the declaration of variable. like: "String _value;", and voila, it worked.
#Sorry for the English, Brazilian here.
In my case, I use FormBuilderDropdown of the package flutter_form_builder.
Adding key: UniqueKey() in the Widget FormBuilderDropdown is the solution for my case.
I had same issue with Getx package. When it's updated, it causes this error because add same items to list. Adding key: UniqueKey() to DropdownButtonFormField is the solution for me.
You must initialise the _value1 and _value2 with a initial Value.
_value1 and _value2 variables need to be initialized, or you can do that:
value: _value1 != null ? _value1 : null,
hint: Text('Your hint'),
var _issues = [
"Subscription Related",
"Talk Therapy Related",
"Program Related",
"Account Related",
"Technology Related",
];
String _currentSelectedValue=_issues.first;
As much as the answer accepted may be working, it is unnecessary and over achieving.
All you need to do is ENSURE THAT whatever your initialized the value to is in the list as well. That is:
String _value1 = "Name1";
If the initialized value is not in your list, you will get the error message you are getting. Period!
If you are sure that your code is right then do "hot restart" instead of "hot reload".
this solved in my case
value: _value1,
onChanged: (value) {
setState(() {
_value1 = value;
_value2 = null;
});
},
The dropdownbuttonformfield filtering mechanism uses a single field for filtering. It can not filter by class hash. Set the DropdownMenuItem value to the key of the incoming data. The dropdownmenuItem value must be unique. The key is String type. currentStatus holds the key to position in the dropdown. I map a list of class objects where the class has databaseValue field and a displayValue field to the dropdownmenuitem as value:databaseValue and child:Text(displayValue). Now, I can set _currentStatus to a databaseValue and it will position in the dropdown.
String _currentStatus;
List<DropdownMenuItem> listMenuItems =
<DropdownMenuItem<String>>[];
Provider.of<Api>(context, listen: false)
.getComboViews()
.then((data) {
setState(() {
listMenuItems =
data.map<DropdownMenuItem<String>>((item) {
return DropdownMenuItem<String>(
value: item.databaseValue, child: Text(item.displayValue));
}).toList();
DropdownButtonFormField<String>(
value: this._currentStatus,
items: listMenuItems
onChanged: (String value) {
setState(() {
this._currentStatus = value;
});
);
String? dropdownValue
hint: Text( "Select City"),
value: dropdownValue == null ? null : dropdownValue,
onChanged: (String? newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: <String>[
'Islamabad',
'RawalPindi',
'Mangla',
'Mirpur'
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
Once you have Multiple DropDownButtons which are dependent on one another.
Adding key: (_value1 != null)
? Key(_value1)
: UniqueKey() to the dependent DropdownButtonFormField
children: <Widget>[
Row(
children: <Widget>[
Text('Name: '),
Center(
child: DropdownButton(
value: _value1,
onChanged: (value) {
setState(() {
_value1 = value;
});
},
items: nameList.map(
(item) {
return DropdownMenuItem(
value: item,
child: new Text(item),
);
},
).toList(),
),
),
],
),
Row(
children: <Widget>[
Text('Name: '),
Center(
child: DropdownButton(
value: _value2,
key: (_value1 != null) ? Key(_value1) : UniqueKey()
onChanged: (value) {
setState(() {
_value2 = value;
});
},
items: nameList.map(
(item) {
return DropdownMenuItem(
value: item,
child: new Text(item),
);
},
).toList(),
),
),
],
You can use the same list in multiple DropDownButton. The error you got is because of having more than one same values in the list.
For Example, if I change the list to given below where I have two items having the same value, it will throw me an error.
`final List<String> nameList = <String>[
"Name1",
"Name1",
"Name3",
"Name4",
"Name5",
"Name6",
"Name7",
"Name8"
];`
Error:
_value1 and _value2 must be in your list
I solved this problem by specifying the type (in my case String): FormBuilderDropdown<String> and setting initialValue: null
I have Flutter 3.3.4
This happens when the value field type is not the same than the types used in items. Here is a example throwing the same error.
FittedBox(
fit: BoxFit.contain,
child: DropdownButton<E>(
//isExpanded: true,
value: box?.get(hiveKey), // hive key = string value --> need to convert to E type
onChanged: (final E? newValue) {
updateSettingsOnTap(box);
},
items: values.map<DropdownMenuItem<E>>((E value) {
return DropdownMenuItem<E>( // --> E type not string
value: value.item,
child: Text(value.getItemValue(), overflow: TextOverflow.ellipsis),
);
}).toList(),
You have to use the same type in value and items fields to fix it. Working code below.
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
FittedBox(
fit: BoxFit.contain,
child: DropdownButton<String>(
//isExpanded: true,
value: box?.get(hiveKey),
onChanged: (final String? newValue) {
updateSettingsOnTap(box);
},
items: values.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value, overflow: TextOverflow.ellipsis),
);
}).toList(),
Here is how I have implemented the dropdowns. This code handles exceptions in case list is not loaded or preselected value does not exist in the list. Also, it does provide validation on selected item.
Following is the Widget implementation ( e.g. froonodropdown.dart)
import 'package:flutter/material.dart';
class FroonoDropDown<T> extends FormField<T> {
final T? selectedValue;
final FocusNode? fnNode;
final void Function(T) onChanged;
final List<T> list;
final String Function(T) getLabel;
final String label;
FroonoDropDown(this.label, this.list, this.selectedValue, this.fnNode, this.onChanged, this.getLabel, {Key? key})
: super(
key: key,
validator: (T? item) {
return item == null ? "Please choose an option" : null;
},
initialValue: list.contains(selectedValue) ? selectedValue : null,
builder: (FormFieldState<T> state) {
List<DropdownMenuItem<T>> dropdownItems = [];
dropdownItems.add(DropdownMenuItem(value: null, child: Text("Select " + label)));
//handle exception in case list is not loaded or selectedValue is not part of the list
T? defaultValue = selectedValue;
if (selectedValue != null && !list.contains(selectedValue)) {
if (getLabel(selectedValue).isEmpty) {
defaultValue = null;
} else {
list.add(selectedValue);
}
}
dropdownItems.addAll(list.map((T item) {
return DropdownMenuItem(
value: item,
child: Text(getLabel(item)),
);
}).toList());
return Column(
children: <Widget>[
InputDecorator(
decoration: InputDecoration(labelText: label),
child: DropdownButtonHideUnderline(
child: DropdownButton(
focusNode: fnNode,
value: defaultValue,
isDense: true,
onChanged: (T? selectedItem) {
state.didChange(selectedItem);
if (selectedItem != null) onChanged(selectedItem);
},
items: dropdownItems),
),
),
if (state.hasError)
Align(
alignment: Alignment.centerLeft,
child: Text(state.errorText!, style: TextStyle(color: Theme.of(state.context).errorColor, fontSize: 12)),
)
],
);
},
);
}
Examples:
With String items:
FroonoDropDown<String>("String Items", stringItemsList, defaultValue, null, (String value) {
defaultValue = value;
//do something else with value;
}, (String item) => item)
With any custom class:
FroonoDropDown<CustomClass>("My Custom List", customClassObjsList,
defaultValue, null, (CustomClass value) {
defaultValue = value;
//do something else with value;
}, (CustomClass act) => act.title)
Make sure you override comparison operator and hashcode in your CustomClass, like this:
#override
bool operator ==(dynamic other) {
return other != null && typeid == other.typeid;
}
#override
int get hashCode => super.hashCode;
I hope above implementation would be useful for you!