Flutter DropdownButton widget with Getx - flutter

I'm in the process of learning GetX state management and stumble upon the DropdownButton widget. How do I update the selected value with the selected value cannot be observed. Here is my DropdownButton widget
DropdownButton(
hint: Text(
'Book Type',
),
onChanged: (newValue) {
print(newValue);
},
value: selectedType,
items: bookController.listType.map((selectedType) {
return DropdownMenuItem(
child: new Text(
selectedType,
),
value: selectedType,
);
}).toList(),
),
The
var selectedType;
declared in the widget build. I tried to make this variable observable but the layout throws an overflow error. I also wrap the widget with obx but still, it throws the same error. How do exactly this widget implement using GetX. I'm pulling my hair here. I can work with other widgets with getX.

First create your controller class.
class BookController extends GetxController {
// It is mandatory initialize with one value from listType
final selected = "some book type".obs;
void setSelected(String value){
selected.value = value;
}
}
On the view, instantiate your Controller and wrap the DropdownButton with an Obx widget:
BookController bookcontroller = BookController();
Obx( () => DropdownButton(
hint: Text(
'Book Type',
),
onChanged: (newValue) {
bookController.setSelected(newValue);
},
value: bookController.selected.value,
items: bookController.listType.map((selectedType) {
return DropdownMenuItem(
child: new Text(
selectedType,
),
value: selectedType,
);
}).toList(),
)
),

if you don't want to use observable variable then wrap your dropdown with getBuilder and in onChange function just update your controller like
onChanged: (newValue) {
bookController.currentDropdownValue=newValue;
bookController.update();
},
Example
//Controller
class HomeController extends GetxController {
var selectedDrowpdown = 'abc';
List dropdownText = ['abc', 'def', 'ghi'];
}
//dropdown button in Ui
DropdownButton(
hint: Text(
'Book Type',
),
onChanged: (newValue) {
homeController.selectedDrowpdown=newValue;
homeController.update();
},
value: homeController.selectedDrowpdown,
items: [
for (var data in homeController.dropdownTextList)
DropdownMenuItem(
child: new Text(
data,
),
value: data,
)
])

final selected = "".obs;
BookController bookcontroller = BookController();
Obx( () => DropdownButton(
hint: Text(
'Book Type',
),
onChanged: (newValue) {
bookController.setSelected(newValue);
},
value: bookController.selected.value==""?null:bookController.selected.value,
items: bookController.listType.map((selectedType) {
return DropdownMenuItem(
child: new Text(
selectedType,
),
value: selectedType,
);
}).toList(),
)
),
Try this, this worked for me.

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!;
});
},
),
),
);
}
}

How can I make dropdownbutton using Getx in flutter?

I'm trying to make dropdownbutton using Getx in flutter
However, it doesn't work.
Even if I choose a value, the value does not been selected.
class BecomePlayerPage2 extends GetView<BecomePlayerController> {
const BecomePlayerPage2 ({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Obx(
() => Scaffold(
body: Padding(
padding: EdgeInsets.all(20),
child:
DropdownButton<RxString>(
onChanged: (newValue){
controller.selected=newValue!;
},
value: controller.selected,
items: [
for(var value in controller.tierList)
DropdownMenuItem(
child: new Text(
value,
),
value: value.obs,
),
]
),
),
),
}
class BecomePlayerController extends GetxController {
final tierList=['first', 'second', 'third'].obs;
var selected = "first".obs;
}
This is my first day of studying Getx so it is so hard to match with basic widget.
What should I do?
Try replacing the onChange statement with
onChanged: (newValue) {
controller.selected.value = newValue.toString();
},
or by changing Dropdown button type from RXString to String
return Obx(
() => Scaffold(
body: Padding(
padding: const EdgeInsets.all(20),
child: DropdownButton<String>( // updated
onChanged: (newValue) {
controller.selected.value = newValue!; //updated
},
value: controller.selected.value, //updated
items: [
for (var value in controller.tierList)
DropdownMenuItem(
value: value,
child: Text(
value, //updated
),
),
]),
),
),
);
Use round brackets to update .obs and change RxString to String
authController.selected(newValue.toString());
onChanged: (newValue){
// controller.selected=newValue!;
controller.selected.value =newValue!;
},

Why isn't my DropdownButtonFormField showing the items?

I have this Dropdown:
DropdownButtonFormField(
value: shipmentSelected,
hint: Text(
'choose one',
),
onChanged: (value){
shipmentSelected = value;
}
items: product.shipment.map((Shipment shipment) {
return DropdownMenuItem(
value: shipment.code,
child: Text(
shipment.code,
),
);
}).toList(),
)
But it doesn't show any item... just show the hintText. How to fix it?
You need to pass a callback function to onChanged in the DropdownButtonFormField constructor. Update shipmentSelected and rebuild from this function like so:
onChanged: (value) {
setState(() {
shipmentSelected = value;
});
},

How do I load a second DropdownButton based on selection from first DropdownButton in Flutter?

I have two dropdowns. Now i want to show secocnd dropdown only when first one is selected otherwise it should be hide.how can i do that in this code please anyone help me.
How can I hide/show widgets on basis of dropdown selection
'How can I hide second dropdown until first is choosen?'
#override
Widget build(BuildContext context) {
loadDatalistDropexpensetype();
loadDatalistDropexpensetype1();
return new Scaffold(
appBar: AppBar( 'appbar'
title: Text("DropDown Testing 2"),
),
body: new Column(
children: <Widget>[
new DropdownButton(
items: listDropexpensetype, 'item which are mentioned in function'
value: select,
hint: Text("select option"),
onChanged: (value){
print(value.toString());
setState(() {
select=value;
});
}
),
Visibility(
visible: tcVisibility,
child: new DropdownButton( 'this should onlt show on selection of first'
items: listDropexpensetype1,
value: selectedexpensetype,
hint: Text("select option"),
onChanged: (value){
print(value.toString());
setState(() {
selectedexpensetype=value;
});
}
),
),
],
),
);
}
}
You can store a temp variable outside of your build function. For example,
String firstDropDownData = "";
In the onChange() function of your first drop-down, simply update the value of "firstDropDownData" and store something relative in it. Once you'll have something in "firstDropDownData", your second dropdown will be rendered automatically in the UI.
Consider wrapping your second drop-down with the following line.
firstDropDownData != "" ? DropdownButton(
items: listDropexpensetype1,
value: selectedexpensetype,
hint: Text("select option"),
onChanged: (value){
print(value.toString());
setState(() {
selectedexpensetype=value;
});
}
) : Container()
UPDATE:
On your request, here's a full demo code:
String firstDropDownData = "";
#override
Widget build(BuildContext context) {
loadDatalistDropexpensetype();
loadDatalistDropexpensetype1();
return Scaffold(
appBar: AppBar( 'appbar'
title: Text("DropDown Testing 2"),
),
body: Column(
children: <Widget>[
DropdownButton(
items: listDropexpensetype,
value: select,
hint: Text("select option"),
onChanged: (value){
print(value.toString());
setState(() {
firstDropDownData = value;
});
}
),
firstDropDownData != "" ? DropdownButton(
items: listDropexpensetype1,
value: selectedexpensetype,
hint: Text("select option"),
onChanged: (value){
print(value.toString());
setState(() {
selectedexpensetype=value;
});
}
) : Container(),
],
),
);
}
}

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!