I have a list of locations that i want to implement as a dropdown list in Flutter. Im pretty new to the language. Here's what i have done.
new DropdownButton(
value: _selectedLocation,
onChanged: (String newValue) {
setState(() {
_selectedLocation = newValue;
});
},
items: _locations.map((String location) {
return new DropdownMenuItem<String>(
child: new Text(location),
);
}).toList(),
This is my list of items:
List<String> _locations = ['A', 'B', 'C', 'D'];
And I am getting the following error.
Another exception was thrown: 'package:flutter/src/material/dropdown.dart': Failed assertion: line 468 pos 15: 'value == null || items.where((DropdownMenuItem<T> item) => item.value == value).length == 1': is not true.
I assume the value of _selectedLocation
is getting null. But i am initialising it like so.
String _selectedLocation = 'Please choose a location';
The error you are getting is due to ask for a property of a null object. Your item must be null so when asking for its value to be compared you are getting that error. Check that you are getting data or your list is a list of objects and not simple strings.
you have to take this into account (from DropdownButton docs):
So basically you have this list of strings
And your value in Dropdown value property is initialised like this:
Just try with this list:
That should work :)
Also check out the "hint" property if you don't want to add a String like that (out of the list context), you could go with something like this:
Try this
Let say we are creating a drop down list of currency:
Add below code in body part:
You need to add
value: location
in your code to work it. Check this out.Change
To
_selectedLocation needs to be part of your item List;