Flutter pass data from DropdownButton to api - flutter

I just wanted to map to api and make the following DropdownButton in flutter that posts data to API when an item is selected
DropdownButton(
value: 'Item 1',
icon: const Icon(Icons.keyboard_arrow_down),
items: [
'Item 1',
'Item 2',
'Item 3',
'Item 4',
'Item 5',
].map((String items) {
return DropdownMenuItem(
value: items,
child: Text(items),
);
}).toList(),
onChanged: print),
how can I map to api endpoint and post the selected item to api?

As a post request with an integer instead of string:
Future<void> onChangedCallback(int? item) async {
if(item != null){
currentValue = item;
final url = "your_url_here";
final body = {
"key_you_want_to_map": item
};
final response = await http.post(Uri.parse(url), body: body);
print(response.body);
}
}
...
var currentValue = 1;
DropdownButton(
value: currentValue,
icon: const Icon(Icons.keyboard_arrow_down),
items: <int>[
1,
2,
3,
4,
5,
].map((int i) {
return DropdownMenuItem(
value: i,
child: Text('Item $i'),
);
}).toList(),
onChanged: onChangedCallback,
), // Equivalent of onChanged: (v) async => onChangedCallback(v),

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 to make today's date default value as dropdown value in flutter?

My dropDown working fine, instead of Today as a string in the dropDown initial value I want Today's date-time using the property DateTime.now()
String dropdownvalue = 'Today';
var items = [
'Today',
'Choose from calendar',
];
My dropdown:
DropdownButton(
underline: Container(),
isExpanded: true,
value: dropdownvalue,
icon: const Icon(
Icons.keyboard_arrow_down,
color: Color(0xffB50000),
),
items: items.map((String items) {
return DropdownMenuItem(
value: items,
child: Text(
items,
style: TextStyle(
color: Color(0xffB50000),
fontWeight: FontWeight.w400),
),
);
}).toList(),
onChanged: (String? newValue) {
setState(() {
dropdownvalue = newValue!;
});
if(dropdownvalue =='Choose from calendar'){
setState(() {
_selectedDate(context);
});
}
if(dropdownvalue =='Today'){
setState(() {
String today = DateFormat('dd-MM-yyyy').format(currentDateTime);
print("today");
print(today);
final storeProvider = Provider.of<StorageProvider>(context, listen: false);
storeProvider.updateAppointmentDate(today);
final slotBookingProvider = Provider.of<SlotBookingProvider>(context, listen: false);
slotBookingProvider.checkAvailableSlot(date: today, context: context);
});
}
},
),
You can
You can replace replacing Today with DateTime.now().toString()
String? dropdownvalue;
var items = [
DateTime.now().toString(),
'Choose from calendar',
];

How to pass Drop Down Value into Database through API using Flutter

This is my list view which is e.g
List<String>items = <String>[
'Leave Type',
'CL',
'SL',
'EL', ];
String dropdownValue = 'Leave Type';
as i Created dropdown here the widget below sample
Padding(
padding:EdgeInsets.all(10.0),
child:
DropdownButton<String>(
iconSize: 24,
elevation: 16,
onChanged:(String? newValue){
setState((){
dropdownValue = newValue!;
});
},
value:dropdownValue,
items:items.map<DropdownMenuItem<String>>(
(String value){
return DropdownMenuItem<String>(
value: value,
child:Text(value),
);
},
).toList(),
)
),
Now want to pass the value into database

I want to create a custom DropdownButton in flutter which can be reusable with different List [Flutter]

Here I have four Lists as in the code below and is it possible to call the list through parameter od any someother way for reusable purpose, example if I have four DropDown Button and each DropDown Button contains different Lists so how i can create a reusable code for implement this.
Here is what i tried,
import 'package:flutter/material.dart';
class CustomDropDown extends StatefulWidget {
final String HintName;
final List<String> MDPT;
CustomDropDown({required this.HintName, required this.MDPT});
#override
_CustomDropDownState createState() => _CustomDropDownState();
}
class _CustomDropDownState extends State<CustomDropDown> {
String? dropdownvalue;
var MDPackageType = [
'Package Type 1',
'Package Type 2',
'Package Type 3',
'Package Type 4',
];
var MDPackageName = [
'Package Name 1',
'Package Name 2',
'Package Name 3',
'Package Name 4',
];
var PTPackageType = [
'Package Type 1',
'Package Type 2',
'Package Type 3',
'Package Type 4',
];
var PTPackageName = [
'Package Type 1',
'Package Type 2',
'Package Type 3',
'Package Type 4',
];
#override
Widget build(BuildContext context) {
return FormField<String>(
builder: (FormFieldState<String> state) {
return InputDecorator(
decoration: InputDecoration(
// labelStyle: textStyle,
// errorStyle: TextStyle(color: Colors.redAccent, fontSize: 16.0),
hintText: 'Package Type',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0),
),
),
isEmpty: dropdownvalue == '',
child: DropdownButtonHideUnderline(
child: DropdownButton<String>(
hint: Text(
widget.HintName,
style: TextStyle(color: Colors.blue),
),
value: dropdownvalue,
isDense: true,
onChanged: (String? newValue) {
setState(() {
dropdownvalue = newValue;
state.didChange(newValue);
});
},
items: MDPT.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(
value,
style: TextStyle(color: Colors.blue),
),
);
}).toList(),
),
),
);
},
);
}
Use the following function to build DropdownMenuItem list using a List.
List<DropdownMenuItem> buildDropdownMenuItems(List list){
List<DropdownMenuItem> dropDownItems = [];
list.forEach((value) {
dropDownItems.add(
DropdownMenuItem<String>(
value: value,
child: Text(
value,
style: TextStyle(color: Colors.blue),
),
)
);
});
return dropDownItems;
}
Use items: buildDropdownMenuItems(MDPT) property to call the function.
So the full code as below.
import 'package:flutter/material.dart';
class CustomDropDown extends StatefulWidget {
final String hintName;
final List<String> MDPT;
CustomDropDown({required this.hintName, required this.MDPT});
#override
_CustomDropDownState createState() => _CustomDropDownState();
}
class _CustomDropDownState extends State<CustomDropDown> {
String? dropdownvalue;
List<DropdownMenuItem<String>> buildDropdownMenuItems(List list){
List<DropdownMenuItem<String>> dropDownItems = [];
list.forEach((value) {
dropDownItems.add(
DropdownMenuItem<String>(
value: value,
child: Text(
value,
style: TextStyle(color: Colors.blue),
),
)
);
});
return dropDownItems;
}
#override
Widget build(BuildContext context) {
return FormField<String>(
builder: (FormFieldState<String> state) {
return InputDecorator(
decoration: InputDecoration(
hintText: widget.hintName,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0),
),
),
isEmpty: dropdownvalue == '',
child: DropdownButtonHideUnderline(
child: DropdownButton<String>(
hint: Text(
widget.hintName,
style: TextStyle(color: Colors.blue),
),
value: dropdownvalue,
isDense: true,
onChanged: (String? newValue) {
setState(() {
dropdownvalue = newValue;
});
},
//call buildDropdownMenuItems() here and pass the list of Strings as attribue
items: buildDropdownMenuItems(widget.MDPT),
),
),
);
},
);
}
}

How to add custom option for my dropdown?

So for now i have a dropdown that i fetch from api. Here is what i do
Future<String> getSWData() async {
var res = await http.get(
Uri.encodeFull(Configuration.url + "api/getCategories"),
headers: {"Accept": "application/json"});
var resBody = json.decode(res.body);
setState(() {
data = resBody;
});
print(data);
return "Sucess";
}
then here is how i use it on dropdown
DropdownButtonHideUnderline(
child: new DropdownButton(
hint: new Text("Choose Category"),
items: data.map((item) {
return new DropdownMenuItem(
child: new Text(item['categoryName']),
value: item['categoryId'].toString(),
);
}).toList(),
onChanged: (newVal) {
setState(() {
mySelection = newVal;
});
},
value: _mySelection, ),),
Everything is working fine, but now i want to add All Category to my dropdown as an option, how can i achieve that ? thanks in advance
Your DropdownButton items is a list, so you can add to that list using ..add
DropdownButtonHideUnderline(
child: new DropdownButton(
hint: new Text("Choose Category"),
items: data.map((item) {
return new DropdownMenuItem(
child: new Text(item['categoryName']),
value: item['categoryId'].toString(),
);
}).toList()
..add(DropdownMenuItem(child: Text("All Category"), value: 'allcategory')),
onChanged: (newVal) {
setState(() {
mySelection = newVal;
});
},
value: _mySelection, ),),
You can use Cascade operator
DropdownButtonHideUnderline(
child: new DropdownButton(
hint: new Text("Choose Category"),
items: data..add({
'categoryName': 'All Categories',
'categoryId': 'AllCategories',
}).map((item) {
return new DropdownMenuItem(
child: new Text(item['categoryName']),
value: item['categoryId'].toString(),
);
}).toList(),
onChanged: (newVal) {
setState(() {
mySelection = newVal;
});
},
value: _mySelection, ),),
this solution will have the effect that "All Categories" item will be last.
You can add "All Categories" item in getSWData().
...
setState(() {
data = List();
data.add({
'categoryName': 'All Categories',
'categoryId': 'AllCategories',
});
data.addAll(resBody);
});
...
I would recommend the second approach, you get better readable code.