How to get multiple values from DropdownButtonFormField in flutter? - flutter

selecting one item from dropdown menu, i want to show its multiple values inside textfields in flutter. For example, if I select school it will show its name, location, contact no. so i need to collect multiple values from that item. how can i have multiple values from dropDownMenuItem to show multiple values?
for example School list item is given below:
"SchoolList": [
{
"name": "school1",
"location": "location1",
"contact_no": "address1"
},
{
"name": "school2",
"location": "location2",
"contact_no": "address2"
},
{
"name": "school3",
"location": "location3",
"contact_no": "address3"
},
],

at first we need to pass Item type as parameter of DropdownButtonFormField. Items will me that type of list and it will return dropDownMenuItem of that type. Then we will assign values from items inside onChanged section.
DropdownButtonHideUnderline(
child: DropdownButtonFormField<
SchoolList>(
validator: (value) => value == null
? 'field required'
: null,
value: selectedItem,
icon: const Icon(
Icons.arrow_drop_down,
color: Colors.grey,
),
iconSize: 24,
elevation: 16,
hint: Text(
'Select',
),
onChanged:
(SchoolList?
schoolList) {
setState(() {
selectedSchoolName =
schoolList!
.name;
selectedSchoolLocation =
schoolList!
.location;
selectedSchoolContactNo
=
schoolList!
.contact_no;
});
},
//
items: =
SchoolList
?.map((item) {
return DropdownMenuItem<
SchoolList>(
value: item,
child:
Text(item.name)),
);
}).toList(),
),
),

Related

Flutter Form Builder loses initialValue when no input exists for field

When using FormBuilder initialValue, it seems the values are not saved when they are not part of an input. Here is an example code snipped
FormBuilder(
initialValue: {
"id": "MyId",
"name": "Name",
},
key: _formKey,
child: Column(
children: [
FormBuilderTextField(
name: "name",
),
TextButton(
onPressed: () {
_formKey.currentState?.save();
if (_formKey.currentState?.validate() == true) {
print(_formKey.currentState!.value);
}
},
child: Text(
"Save",
),
)
],
),
)
When pressing save and inspecting the values of the form state it has only name but is missing the id attribute.
Is this intended behavior and if so, is it possible to make it keep the id field?

Searchable Dropdown search is not working when i access the id as value inside DropdownMenuItem | Flutter

Iam using searchable_dropdown: ^1.1.3 package to search elements in dropdownmenu, when i use district (which give district name) for the value inside DropdownMenuItem it works properly. But the problem is when a user selects district i want the value as districtId. but when i give districtId as value the search is not working. Below is my code.
Center(
child: SearchableDropdown.single(
isExpanded: true,
value: selectedName,
hint: "Select one",
searchHint: "Select one",
// hint: Text('Select Name'),
items: districtList.map(
(list) {
return DropdownMenuItem(
child: Text(list['district']),
value: list['districtId'],
);
},
).toList(),
onChanged: (value) {
setState(() {
selectedDistrict = value;
print(selectedDistrict );
});
},
),
),
This is the package https://pub.dev/packages/searchable_dropdown

Flutter: How to retrieve the data from firebase and show in the dropdown field

I am developing a Flutter application where I need to show the category field as a dropdown. I have added the category field as a dropdown in the form. I need to retrieve the data from Firebase for the category field and I have succeeded in getting the data but the problem is, it is not showing the entire data from the collection rather it is showing only one piece of data from the collection in the category dropdown field. How do I show the entire data from the collection? Please help me with your answer. Thanks!!
Here is the code for getting data from Firebase Collection
String _category;
void _onCategory() async {
_firestore.collection("categories").get().then((querySnapshot) {
querySnapshot.docs.forEach((result) {
print(result.data()['category']);
setState(() {
_category = result.data()['category'] ;
});
});
});
}
This is the code for showing the category data in the dropdown
String _dropDownValue;
Widget _categoryInput(){
return Padding(
padding: const EdgeInsets.only(top: 20.0),
child: DropdownButton(
hint: _dropDownValue == null
? Text('Category', style: TextStyle(color: Theme.of(context).primaryColor),)
: Text(
_dropDownValue,
style: TextStyle(color: Colors.white),
),
isExpanded: true,
iconSize: 30.0,
style: TextStyle(color: Colors.black),
items: ['$_category'].map(
(val) {
return DropdownMenuItem<String>(
value: val,
child: Text(val),
);
},
).toList(),
onChanged: (val) {
setState(
() {
_dropDownValue = val;
},
);
},
),
);
}

Type 'String' is not a subtype of Map<Dynamic, Dynamic>

I have a dart file that stores the list of map of country names and dial codes. The format is thus...
countries = List<Map> countries = [ { "name": "Afghanistan", "dial_code": "+93", "code": "AF" }, { "name": "Ă…land Islands", "dial_code": "+358", "code": "AX" } ]
I imported it into my main file with my buttondropdown file and tried using the map function on it.
child: DropdownButtonFormField(
decoration: InputDecoration(
border: InputBorder.none,
prefixIcon: Icon(Icons.location_city,
color: Colors.white)),
items: countries
.map((Map<String, String> dropDownStringItem) {
return DropdownMenuItem<String>(
value: dropDownStringItem,
child: Text(dropDownStringItem),
);
}).toList(),
onChanged: (value) {
setState(() {
print(value);
});
},
),
Am trying to make the dropdown show just the names. But I get the error type 'String' is not a subtype of type Map. WHat am i doing wrong
Specifying type Map by itself will make the compiler assume that it is of type Map<dynamic, dynamic>. You need to change this line:
items: countries.map((Map dropDownStringItem) {
To this:
items: countries.map((Map<String, String> dropDownStringItem) {

creating textbox from list in flutter

I have List like this (It keeps changing because this is the response of API,
tableValue=[
{
"id": "RegNo",
"displayName": "Enter Register No",
"type": "string",
"value": "1XYZ19AA"
},
{
"id": "name",
"displayName": "Enter Name",
"type": "string",
"value": "KARAN"
},
{
"id": "sub",
"displayName": "choose subjects",
"type": "list",
"value": ["JAVA"],
"data": [
{"id": "1", "dispId": "JAVA"},
{"id": "2", "dispId": "Python"},
{"id": "3", "dispId": "Dart"}
]
}
];
What I want to display is like below,
Based on the List, I want to display all its data,
i.e
Enter Register No --Text_Box here--
Enter Name --Text_Box here--
(How many entries have string type I want to display a text box with its display name and a value defined in the List for that map should be displayed example 1XYZ19AA on the textbox),
If there are n entries with the type string n text box with the display name should be displayed, and I want to have the control over the data entered.
If there are 3 text boxes in the list if the user enters all or only 1 I should be able to access that uniquely.
Question
Can you suggest any way of displaying if its a type list, because elements in a list should have a multi-select option?
Thank you
ListView.builder(
itemCount: tableValue.length,
itemBuilder:(context, index){
return Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height/10,
child: Row(
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width/2,
height: MediaQuery.of(context).size.height/10,
alignment: AlignmentDirectional.centerStart,
child:Text(tableValue[index]['displayName'])
),
Container(
width: MediaQuery.of(context).size.width/2,
height: MediaQuery.of(context).size.height/10,
alignment: AlignmentDirectional.centerStart,
child: TextField(
decoration: InputDecoration.collapsed(
hintText: "blah"
)
)
)
],
)
);
}
)
Here is an example where you can show the data from the table and also you can see how to access the selected values of the TextFields and Checkboxs
Note that you may need to change the type of tableValue like this:
List<Map<String, dynamic>> tableValue = [...]
Map<String, TextEditingController> controllers = {};
Set<String> checks = {};
This would be the body of your screen
ListView(
children: <Widget>[
Column(
children: tableValue
.where((entry) => entry["type"] == "string")
.map((entry) => Row(
children: <Widget>[
Text(entry["displayName"]),
Flexible(
child: TextField(
controller: getController(entry["id"]),
),
)
],
)).toList(),
),
Column(
children: tableValue
.firstWhere(
(entry) => entry["type"] == "list")["data"]
.map<Widget>(
(data) => CheckboxListTile(
title: Text(data["dispId"]),
value: checks.contains(data["id"]),
onChanged: (checked) {
setState(() {
checked ? checks.add(data["id"]) : checks.remove(data["id"]);
});
},
),
).toList(),
),
Text("Texts: ${controllers.values.map((controller) => controller.text)}"),
Text("Checks: ${checks.map((check) => check)}"),
],
)
And this is how you could handle the TextField controllers
TextEditingController getController(String id) {
controllers.putIfAbsent(id, () => TextEditingController());
return controllers[id];
}