Dropdown list not showing selected value - flutter

I have a dropdown list that gets its value from firebase and when I'm trying to pick a value, it shows me an error.
There should be exactly one item with [DropdownButton]'s value: vff.
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 850 pos 15: 'items == null || items.isEmpty || value == null ||
items.where((DropdownMenuItem<T> item) {
return item.value == value;
}).length == 1'
here's the source code, I was adding values to dropdown list by using loop, and giving value by name of query
return StreamBuilder<List<CoursesRecord>>(
stream: queryCourseRecord(
queryBuilder: (courseRecord) => courseRecord.orderBy(/*widget.orderBy*/'${widget.orderBy}', descending: true), limit: 5,
),
builder: (context, snapshot) {
// Customize what your widget looks like when it's loading.
if (!snapshot.hasData) {
return Center(
child: SizedBox(
width: 50,
height: 50,
child: CircularProgressIndicator(
color: FlutterFlowTheme.primaryColor,
),
),
);
}
List<CoursesRecord> listViewCourseRecordList = snapshot.data;
for (int i = 0; i < 2; i++) {
String value = listViewCourseRecordList[i].name;
courseItems.add(
DropdownMenuItem(
child: Container(
width: 316 ,
child: CourseBoxName(coursesRecord: listViewCourseRecordList[i],)),
value: value,
),
);
}
// Customize what your widget looks like with no query results.
if (snapshot.data.isEmpty) {
return Container(
height: 100,
child: Center(
child: Text('No results.'),
),
);
}
return Container(
width: MediaQuery.of(context).size.width,
height: 100,
child: DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton(
value: selected,
isDense: true,
items: courseItems,
hint: Text(
"Выберите курс",
),
onChanged: (newValue) {
setState(() {
selected = newValue;
widget.courseSelected(newValue);
});
},
isExpanded: false,
),
),
),
);
},
);
So what can I do to fix this problem, I have stuck with it already for several hours T_T

You got null value so for check conditions like droupdownvalue ?? "xyz"
So you can see XYZ when you got a null value.

it looks like you keep adding items to a list with every build without clearing it
on first build you add 1,2,3 and the list contains [1,2,3]
on second build you add the same items even though they didn't change, and the list contains [1,2,3,1,2,3] which clearly contains duplicates
remove courseItems field and the for loop, then tweak the button definition like following:
DropdownButton(
value: selected,
isDense: true,
items: [
for (int i = 0; i < 2; i++)
DropdownMenuItem(
child: Container(
width: 316,
child: CourseBoxName(
coursesRecord: listViewCourseRecordList[i],
)),
value: value,
)
],
hint: Text(
"Выберите курс",
),
onChanged: (newValue) {
setState(() {
selected = newValue;
widget.courseSelected(newValue);
});
},
isExpanded: false,
)

Related

How to validate a form that has cards to select from and the user should obligatorily select one of them?

I have a code whereby the genders of a pet is listed in two separate cards and when the user taps on one of them, it changes color to indicate that it has been selected and is saved in the database. However, the app is letting the user continue to the next page without choosing any one of the values. I want to do a validation whereby the user will have to choose one of the cards to be able to move forward. How can I do this please?
Here is my code:
Expanded(
child: GridView.count(
crossAxisCount: 2,
primary: false,
scrollDirection: Axis.vertical,
children: List.generate(petGenders.length, (index) {
return GestureDetector(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0)),
color:
selectedIndex == index ? primaryColor : null,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
petGenders[petKeys[index]],
SizedBox(
height: 15.0,
),
Text(
petKeys[index],
style: TextStyle(
color: selectedIndex == index
? Colors.white
: null,
fontSize: 18.0,
fontWeight: FontWeight.w600),
),
],
),
),
),
onTap: () {
setState(() {
widget.pet.gender = petKeys[index];
selectedIndex = index;
});
});
}),
),
),
The model:
Map<String, Image> genders() => {
"Male":
Image(image: AssetImage('Assets/images/male.png'), width: 50),
"Female":
Image(image: AssetImage('Assets/images/female.png'), width: 50)
};
Take one variable
bool isGenderSelected = false;
Then change its value to true on tap of card like
onTap: () {
setState(() {
isGenderSelected = true;
widget.pet.gender = petKeys[index];
selectedIndex = index;
});
});
Now check if it's true then only allow the user to go next page or show some message to the user
Scenario like this, I prefer using nullable selectedValue. In this case, I will create nullable int to hold and switch between selection.
int? selectedIndex;
And using color will be like
color: selectedIndex==index? SelectedColor:null,
you can replace null with inactive color.
For validation part, do null check on selectedIndex .
if(selectedIndex!=null){.....}

Flutter did future widget didnt update screen ? i need to update data when its updated

I have an array which i set as a class like this
class FilterArray {
static var FilterArrayData = [];
}
I am simply adding the values in an array. Issue is i am calling this array in a page when array is null. Then on next Page i am adding values in array. Now issue is when i come back in previous page the array is still null. I need to refresh page for this. Which i dont want thats why i use FutureWidget i though from Future widget when array update it will also update in my screen but thats not working. Need to know what can i do for this here i need to update data when array is update so it can show in a Future Widget.
This is my total code
class _SearchPgState extends State<SearchPg> {
Future getData() async {
var result = FilterArray.FilterArrayData;
if (result.length != 0) {
return result;
} else {
return null;
}
}
#override
Widget build(BuildContext context) {
print(FilterArray.FilterArrayData);
return Scaffold(
appBar: AppBar(
title: Container(
height: 50.0,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 3.0),
child: Center(
child: TextField(
onTap: () => Get.to(SearchPgExtra()),
readOnly: true,
decoration: InputDecoration(
hintText: tr('search.search'),
alignLabelWithHint: true,
hintStyle: Theme.of(context).textTheme.subtitle2,
prefixIcon: Icon(Icons.search),
),
),
),
),
),
actions: [
IconButton(
icon: Icon(
FlutterIcons.sort_descending_mco,
color: Theme.of(context).accentColor,
),
onPressed: navigateToSortPage,
),
IconButton(
icon: Icon(
FlutterIcons.filter_fea,
color: Theme.of(context).primaryColor,
),
onPressed: navigateToFilterPage,
),
],
),
body: FutureBuilder(
future: getData(), // async work
builder: (context, projectSnap) {
print(projectSnap.data);
if (projectSnap.hasData) {
return StaggeredGridView.countBuilder(
itemCount: projectSnap.data.length,
crossAxisCount: 4,
staggeredTileBuilder: (int index) => StaggeredTile.fit(2),
mainAxisSpacing: 15.0,
crossAxisSpacing: 15.0,
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: ScrollPhysics(),
padding: EdgeInsets.symmetric(horizontal: 18.0),
itemBuilder: (context, index) {
var product = projectSnap.data[0][index];
return FadeInAnimation(
index,
child: ProductCard2(
product: product,
isHorizontalList: false,
),
);
},
);
} else {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Image.asset(
'assets/images/search.png',
width: MediaQuery.of(context).size.width / 2,
),
SizedBox(height: 15.0),
Text(
'search.title',
style: Theme.of(context).textTheme.headline1,
).tr(),
SizedBox(height: 15.0),
Text(
'search.subtitle',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.subtitle1,
).tr(),
SizedBox(
height: MediaQuery.of(context).size.height / 5,
),
],
),
);
}
},
),
);
}
}
In start array is null then ill add values in array then comeback nothing change then i reload the screen then its working fine.
This is the how i am adding array
RangeSlider(
values: _currentRangeValues,
min: 0,
max: 10000,
divisions: 10,
labels: RangeLabels(
_currentRangeValues.start.round().toString(),
_currentRangeValues.end.round().toString(),
),
onChanged: (RangeValues values) {
setState(() {
_currentRangeValues = values;
//print(_currentRangeValues);
});
var data = searchArray.searchArrayData;
for (int i = 0; i < data.length; i++) {
var current = data[i];
if(current['Price'] >= _currentRangeValues.start && current['Price'] <= _currentRangeValues.end){
print(data);
FilterArray.FilterArrayData.add(data);
}
}
},
),
when data add to FilterArrayData ill go back on Page array on that page not updating so then i change the page and comeback again in SearchPg then i can see data
Don't do your validation with the length of your array. It is like trying to do a validation with something that doesn't existe yet. Instead of that, try using
if(snapshot.hasData)
{ return ... ; }
then, after that, now you can do another validation, for instance, sometimes what you receive is data, but an empty array. There is where I would place the other two options. Remember, inside of the first if.
if(array.isNotEmpty)
{ return ... ; }
and
else
{ return ... ; }
After the first if, then you can now also validate, what will happen if you didn't receive data at all. Simply with an else.
else
{ return ... ; }
In summary: use one first validation with hasData and then, inside of that, decide what to do with the received information. Outside all that, decide what to do if you didn't receive any information at all.
Such cases are faced by new developers often. The best way to deal with it is state management packages like Provider, Bloc, etc. Visit the link and you will find all the relevant packages. Personally, I have used Provider a lot. Bloc is also a good option. A lot of people use it. But I haven't had the chance to use it. Riverpod is an up and coming package. But it still requires a lot of fixing.

add separate values to DropDownButton

I have a widget with a item builder. In the item builder I want to create Drop down for each item.
For the value property of this DropdownMenuItem i use
SaleRef _selectedRef;
The problem is when I declare this SaleRef _selectedRef; inside the itemBuilder the value does not change after selecting a item.
When I declare it outside this widget but in the class it changes the value of every dropdown
What can I do to select separate values on every drop down ?
This is the code for creating the items
ListView.separated(
itemBuilder: (context, index) {
return Row(
children: <Widget>[
Container(
height: 40,
width: MediaQuery.of(context).size.width * 1 / 5,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: new BorderRadius.circular(25.0),
border: Border.all(
color: Colors.grey,
style: BorderStyle.solid,
width: 0.80),
),
child: DropdownButton<SaleRef>(
hint: Text(" Select Ref"),
value: _selectedRef,
onChanged: (SaleRef value) {
setState(() {
_selectedRef = value;
print(_selectedRef.refID);
});
},
items: _filteredSaleRef.map((SaleRef ref) {
return DropdownMenuItem<SaleRef>(
value: ref,
child: Row(
children: <Widget>[
Text(
" " + ref.refName,
style: TextStyle(color: Colors.black),
),
],
),
);
}).toList(),
),
),
],
);
},
separatorBuilder: (context, index) {
return Divider(height: 16);
},
itemCount: filteredShopItem.length,
)
When I declare it like this
class _AssignRefPageState extends State<AssignRefPage>
with {
SaleRef _selectedRef;
This happens after selecting a value
When I declare it like this inside the builder like this
itemBuilder: (context, index) {
SaleRef _selectedRef;
return Row(
This is what I get it's always the hint even after I select a one
The problem is you are using the same variable for every dropdownbutton and when you try to declare it in the ListView itemBuilder and you call setState the whole Widget is built setting it to null again
What you can do is create a List of values(the size should be number of dropdownbuttons you have)
Like this
class _AssignRefPageState extends State<AssignRefPage>
with {
List<SaleRef>_selectedRef = List.generate(numberOfDropDowns, (index) => SaleRef());
Then use the array in your setState
DropdownButton<SaleRef>(
hint: Text(" Select Ref"),
value: _selectedRef,
onChanged: (SaleRef value) {
setState(() {
_selectedRef[index] = value;
print(_selectedRef[index].refID); //<- The index is from itemBuilder
});
}
As #Josteve-Adekanbi said the problem was using the same variable
Creating an array with a size outside the class helped me solve my problem
List<SaleRef> _selectedRef = new List(filteredShopItem.length);
Then I used it like this
DropdownButton<SaleRef>(
hint: Text(" Select Ref"),
value: _selectedRef[index],
onChanged: (SaleRef value) {
setState(() {
_selectedRef[index] = value;
print(_selectedRef[index].refID);
});
}

Flutter function error: Column's children must not contain any null values, but a null value was found at index 1

After I separate a dropdown list to a separate method in flutter, the debugger returns the following error:
"Column's children must not contain any null values, but a null value was found at index 1"
This is the code I had to a separate method _actionDropdown():
_actionDropdown() {
DropdownButton<String>(
value: actionValue,
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(
color: Colors.deepPurple
),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
// if(dropdownValue == 'Move to...') {
// return Text('add chips for folders here');
// } else if(dropdownValue == 'Label as...') {
// return Text('add chips for labels here');
// }
});
},
items: <String>['Archive', 'Delete', 'Move To...', 'Label as...']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
})
.toList(),
);
}
This chunk of code for DropdownButton<String>works as a column child but not when I add the separated method _actionDropdownas a child. What am I missing?
As #brendan suggested you forgot to add return keyword.
_actionDropdown() {
return DropdownButton<String>( // return added here
value: actionValue,

Flutter: There should be exactly one item with [DropdownButton]'s value

I am trying to create a dropdown button in Flutter. I am getting a List from my database then I pass the list to my dropdownButton everything works the data is shown as intended but when I choose an element from it I get this error:
There should be exactly one item with [DropdownButton]'s value: Instance of 'Tag'.
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 805 pos 15: 'items == null || items.isEmpty || value == null ||
items.where((DropdownMenuItem<T> item) {
return item.value == value;
}).length == 1'
I tried setting DropdownButton value to null it works but then I can't see the chosen element.
Here is my code:
FutureBuilder<List<Tag>>(
future: _tagDatabaseHelper.getTagList(),
builder: (BuildContext context, AsyncSnapshot<List<Tag>> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView(
children: <Widget>[
SizedBox(
height: MediaQuery.of(context).size.height * 0.2,
),
Container(
margin: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.width * 0.07),
child: Theme(
data: ThemeData(canvasColor: Color(0xFF525A71)),
child: DropdownButton<Tag>(
value: _selectedTag,
isExpanded: true,
icon: Icon(
Icons.arrow_drop_down,
size: 24,
),
hint: Text(
"Select tags",
style: TextStyle(color: Color(0xFF9F9F9F)),
),
onChanged: (value) {
setState(() {
_selectedTag = value;
});
},
items: snapshot.data.map((Tag tag) {
return DropdownMenuItem<Tag>(
value: tag,
child: Text(
tag.tagTitle,
style: TextStyle(color: Colors.white),
),
);
}).toList(),
value: _selectedTag,
),
),
),
I used futureBuilder to get my List from database.
Well, since no problem has an exact same solution. I was facing the same issue with my code. Here is How I fixed this.
CODE of my DropdownButton:
DropdownButton(
items: _salutations
.map((String item) =>
DropdownMenuItem<String>(child: Text(item), value: item))
.toList(),
onChanged: (String value) {
setState(() {
print("previous ${this._salutation}");
print("selected $value");
this._salutation = value;
});
},
value: _salutation,
),
The Error
In the code snippet below, I am setting the state for a selection value, which is of type String. Now problem with my code was the default initialization of this selection value.
Initially, I was initializing the variable _salutation as:
String _salutation = ""; //Notice the empty String.
This was a mistake!
Initial selection should not be null or empty as the error message correctly mentioned.
'items == null || items.isEmpty || value == null ||
And hence the crash:
Solution Initialize the value object with some default value. Please note that the value should be the one of the values contained by your collection. If it is not, then expect a crash.
String _salutation = "Mr."; //This is the selection value. It is also present in my array.
final _salutations = ["Mr.", "Mrs.", "Master", "Mistress"];//This is the array for dropdown
Might also get this error if trying to set value of dropdown with a class instance;
var tag1 = Tag();
var tag2 = Tag();
print(tag1 == tag2); // prints false, dropwdown computes that value is not present among dropdown options
To solve this override operator ==:
class Tag{
String name = "tag";
#override
bool operator ==(Object other) => other is Tag && other.name == name;
#override
int get hashCode => name.hashCode;
}
or use https://pub.dev/packages/equatable lib
class Tag extends Equatable{
String name = "tag";
#override
List<Object> get props => [name];
}
I had the same problem. The solution is simple: you have to be sure that the String that is your default dropdownvalue is contained in the list that you want to use in your dropdownmenu. If you wanted to, let’s say, use a list from an api, you should be sure to know at least one value of that list, so that you could assign it to the variable that is your default dropdownvalue.
Here I want display a list that I obtain from an api. In order to not obtain the error, I set my defaultdropdownvalue with the name ‘Encajes’ that is one of the existing categories that my list contains.
String dropdownValue = "Encajes";
items: categoriesString
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
Code of my dropdown
child: DropdownButton(
items: _currencies.map((String value) {
return DropdownMenuItem<String>(
child: Text(value),
value: value,
);
}).toList(),
value: 'Rupees',
onChanged: (String newValueSelected) {
// Your code to execute, when a menu item is selected from
dropdown
},
))
var _currencies = ['Rupee','Dollar','Pound'];
I faced same error because the value in the dropdown code block is not matching with any of the fields in _currencies
Okay, some of the answers on this thread will definitely help you resolve the issue. But it is important to clarify why this issue occurs in the first place and what the DropdownButton expects from you.
To give you a little background on the issue it is important to understand how two instances of dart objects are compared.
You will very likely not see the above error if your DropdownButton is dealing with a List of int, String, bool, etc.
This is because you can directly compare primitive types and you would get the expected result.
for instance
int x = 5;
int z = 10;
int y = 5;
String foo= 'hello';
String bar = 'hello;
x == z; // false
x == y; // true
foo == bar; // true
But when dealing with Custom Objects you have to be extra careful and you must ensure you override the "==" operator so that dart knows how to compare instances of your custom object. By default, two objects are equal if they are of the same instance.
consider the Tag class,
class Tag{
final String name;
final String code;
Tag({this.name,this.code});
}
final tag1 = Tag(name:'foo', code: 'hello');
final tag2 = Tag(name:'foo', code: 'hello');
Tag tag3 = tag1;
when you compare
tag3==tag1 dart would return true as expected, But when you compare tag1 == tag2, the dart would return false, since both objects are not of the same instance.
So to deal with this issue you need to override the == operator as shown below
class Tag{
final String name;
final String code;
Tag({this.name,this.code});
#override
bool operator ==(Object other){
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is Tag &&
other.name == name &&
other.code == code
}
}
Now when you compare tag1 ==tag2 it would return true.
This is documented in the official docs here https://dart.dev/guides/language/effective-dart/design#equality
Coming to the DropdownButton error it expects
items is not null
items is not empty
value is not null
value must be present only once in items
Point 4 would fail if you are using Custom objects without overriding the == operator and hence you would get the above error.
TLDR;
So to deal with the error, ensure the above 4 points satisfy and override the == operator so that dart can compare instances of your Tag class as you would expect.
just make the tag class extend from Equatable and pass the attributes to the props.. this did the trick for me.
class Tag extends Equatable{
String id;
String name;
Tag(this.id, this.name);
#override
List<Object> get props => [id,name];
}
I have had the same issue and surprisingly, there were duplicates in my list of items which were being fetched from a remote DB.
Each time I fetched the data from the server (when a new app user logged in), the data had no duplicates but the same data was being added to the list multiple times because I was logging in multiple users on the same device. Maybe your bug is something similar.
So, make sure you remove any duplicates in the snapshot.data before setting them as items of the DropDownButton.
i had the same Error and my default value was not present in the listItems was mapping in the Dropdown Button as :
String defaultvalue = 'selectCategorie'
const List<String> Subcategories = ['category 1','category 2','category 3'...];
Had to Change to this :-
String defaultvalue = 'selectCategorie';
const List<String> Subcategories = ['selectCategorie','category 1','category 2','category 3'...];
now when you pass the defaultvalue in the DropdownButton no errors
DropdownButton (
item:[]
onChanged: (String values){
print(values);
setState(() {
defaultValue = values;
});
},
value: defaultValue,
)
I used a trick. The selected item make as first index item in the list .So when changing item at every time remove the item from list and reinsert the item as first item in the list . Please refer the below code. Here iam using Object as the drop down item and the widget i make it as extracted function. and also before calling the dropDownButton function make
//items list like below
List<LeaveType> items = [
(id=1,name="Sick"),
(id=2,name="Paid")
]
selectedLeave = null;
Row leaveTypeDropDown(StateSetter setCustomState, List<LeaveType> items) {
if(selectedLeave != null){
items.remove(selectedLeave);
items.insert(0, selectedLeave);
}
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children : [
text("Select Leave Type",textSize: 15),
Padding(padding: const EdgeInsets.all(5)),
Expanded(
child: Container(
padding: const EdgeInsets.only(left: 10.0, right: 10.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.black,width: 1),
borderRadius: const BorderRadius.all(Radius.circular(10.0)),
),
child: DropdownButtonHideUnderline(
child: DropdownButton<LeaveType>(
isExpanded: true,
//initial value
value: selectedLeave != null ? items[0] : null,
icon: const Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
hint: text("Leave Type"),
style: const TextStyle(
color: Colors.black
),
onChanged: (LeaveType value) {
setCustomState(() {
selectedLeave = value;
items.remove(selectedLeave);
items.insert(0, selectedLeave);
});
},
items: items
.map((leave) {
return new DropdownMenuItem<LeaveType>(
value: leave,
child: text(leave.name),
);
}).toList(),
),
),
),
),
]
);
}
I changed as below and it got solved:
Initial Code:
List<GamesModel> users = <GamesModel>[
new GamesModel(1,"Option1"),
new GamesModel(2,"Option2"),
];
return users;
Changed Code:
List<GamesModel> users = <GamesModel>[
const GamesModel(1,"Option1"),
const GamesModel(2,"Option2"),
];
return users;
If anybody want i can put the whole code
Note that if the list has duplicated values, it will also has this error.
For example, if languages = ["English", "English", "French"];
then if I set the default language = "English".
DropdownButton<String>(
value: language,
icon: const Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: const TextStyle(color: AppColors.highLightTextColor),
underline: Container(
height: 1,
color: AppColors.underLineColor,
),
onChanged: (String? newValue) async {
setState(() {
language = newValue;
});
},
items: languages.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
Remove the duplicate values, then it works.
So I found a solution.
I created empty List to hold my Tag objects.
List<Tag> _tagList = [];
Then, in my initState i assigned the list i get from database to the previous List
#override
void initState() {
super.initState();
_tagDatabaseHelper.getTagList().then((foo) {
setState(() {
_tagList = foo;
});
});
}
Finally My DropdownButton code :
DropdownButton<Tag>(
isExpanded: true,
icon: Icon(
Icons.arrow_drop_down,
size: 24,
),
hint: Text(
"Select tags",
style: TextStyle(color: Color(0xFF9F9F9F)),
),
items: _tagList.map((foo) {
return DropdownMenuItem(
value: foo,
child: Text(foo.tagTitle),
);
}).toList(),
onChanged: (value) {
setState(() {
_selectedTag = value;
});
},
value: _selectedTag,
),
In my case, i use empty String for default
value : dropdownValue != "" ? dropdownValue : null
Like this, errors be gone
The exact answer is:
keep "value" null before user selection:
String selectedValue = '';
And in the DropdownButton2 Widget:
...
value: selectedValue.isEmpty ? null : selectedValue,
...
It says if selectedValue is empty then give null but when user select a value then give selectedValue
you can avoid the null value using a ternary operator:
Container(
child:
new DropdownButton<String>(
value: dropdownValue ?? "1",
icon: const Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: const TextStyle(color: Colors.black, fontSize: 18),
underline: Container(height: 2, color: Colors.white24, ),
items: <String>['1', '2', '3', '5'].map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);}).toList(),
onChanged: (value) {
setState(() { dropdownValue=value;});
},
)),
This error also occurs if you forget to give dropdown menu items a value.
==== WORKS ====
<String>['A', 'B', 'C'].map<DropdownMenuItem<String>>((vehicle) {
print("vehicle is $vehicle");
print("vehicle is equal ${vehicle == x.value}");
return DropdownMenuItem<String>(
value: vehicle,
child: Text(
// vehicle.vehicleInfo!.vehicleType!,
vehicle,
style: TextStyle(
color: Colors.grey[600],
),
),
);
}).toList(),
==== DOESNT WORK ====
<String>['A', 'B', 'C'].map<DropdownMenuItem<String>>((vehicle) {
return DropdownMenuItem<String>(
child: Text(
vehicle,
style: TextStyle(
color: Colors.grey[600],
),
),
);
}).toList(),
DropdownButton<String>(
iconEnabledColor: Colors.cyan.withOpacity(.6),
isExpanded: true,
itemHeight: 50,
iconSize: 30,
hint: Text("Choose Province"),
items: _provinces
.map((e) => DropdownMenuItem(
child: Text(e),
value: e,
))
.toList(),
value: _Province,
onChanged: (String? value) async{
final respnose=await FirebaseFirestore.instance.collection('city').where('provinceName',isEqualTo: value).get();
_city=[];
for(var item in respnose.docs){
print(item.data());
_city.add(item.data()['name']);
}
print(_Province);
setState(() {
_city=_city;
_Province = value;
});
},
),
SizedBox(height: 20,),
DropdownButton<String>(
iconEnabledColor: Colors.cyan.withOpacity(.6),
isExpanded: true,
itemHeight: 50,
iconSize: 30,
hint: Text("Choose City"),
items:_city
.map((e) => DropdownMenuItem(
child: Text(e),
value: e,
))
.toList(),
value: _City,
onChanged: (String? value) async{
setState(() {
_town=[];
_Town=null;
});
print(_town);
final respnose=await FirebaseFirestore.instance.collection('town').where('cityName',isEqualTo: value).get();
print(respnose.docs);
for(var item in respnose.docs){
print(item.data());
_town.add(item.data()['name']);
}
print(_town);
print(_City);
setState(() {
_City = value;
_town=_town;
});
},
),
SizedBox(height: 20,),
if(true)
DropdownButton<String>(
iconEnabledColor: Colors.cyan.withOpacity(.6),
isExpanded: true,
itemHeight: 50,
iconSize: 30,
hint: Text("Choose Town"),
items:_town
.map((e) => DropdownMenuItem(
child: Text(e),
value: e,
)
)
.toList(),
value: _Town,
onChanged: (String? value)async {
print(_Town);
setState(() {
_Town = value;
});
I had the same problem, and the solution is to fill the value of DropdownButton(value: (use a value from the items you set)
you can not use any value you want, but it should be one of the items that you set for the DropdownMenuItem.
I think because of the update in the framework, the error came out
Here is how you can solve it
DropdownButton(
hint: const Text("Please choose your gender"),
items: <String>["Male", "Female", "Rather not say"]
.map<DropdownMenuItem<String>>((e) {
return DropdownMenuItem<String>(
value: e, child: Text(e.toString()));
}).toList(),
onChanged: (String? value) {
setState(() {
dropdownValue = value!;
});
});
Note that: dropdownValue is a string variable defined at the top
If you are loading the list from an api that returns list, look at what i did to debug the error.
Created a reusable widget that handle future response
Widget rangeLists(selectedValue) {
return FutureBuilder(
future: YourFuture,//this should return Future<List>
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Text('Loading...');
} else {
List<DropdownMenuItem<String>> categoriesItems = [
DropdownMenuItem(
child: Text(selectedValue),
value: selectedValue,
),
];
print('categoriesItems.last.value');
print(categoriesItems.last.value);
var snapshotAsMap = snapshot.data as List;
for (int i = 0; i < snapshotAsMap.length; i++) {
if (snapshotAsMap[i]['category'] != selectedValue) {
categoriesItems.add(
DropdownMenuItem(
child: Text(snapshotAsMap[i]['category']),
value: snapshotAsMap[i]['category'],
),
);
}
}
return Padding(
padding: const EdgeInsets.only(left: 18.0, right: 18, top: 10),
child: Container(
padding: EdgeInsets.only(left: 25, right: 25),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey, width: 1),
borderRadius: BorderRadius.circular(25)),
child: DropdownButton<String>(
items: categoriesItems,
icon: const Icon(
Icons.expand_more,
color: Colors.grey,
),
iconSize: 24,
elevation: 16,
isExpanded: true,
style: const TextStyle(color: Colors.grey),
underline: SizedBox(),
onChanged: (value) {
setState(() {
widget.selectedValue = value;
});
},
value: selectedValue,
hint: Text('My courses'),
),
),
);
}
})};
2.Usage
you can called it like this
String selectedValue="Select Here"
rangeLists(selectedValue)//call this as a widget in ur ui
It will handle all list from the Api backend when u return a list u don't need to worry about the error any more
child: DropdownButtonFormField<String>(
hint: Text(widget.hintText == "Select value..."
? "Select ${widget.caption}"
: widget.hintText),
items: getItems(),
value: **checkValue(widget.currentValue)**,
iconSize: 30,
onChanged: widget.onChanged,
),
String? **checkValue(String? value)** {
var arrRet = widget.items.where(
(item) => item[widget.valueMember].toString() == value.toString());
if (arrRet.isEmpty && widget.items.isNotEmpty)
return widget.items[0][widget.valueMember].toString();
return value;
}