How to get selected item's index number in DropdownButton in Flutter? - flutter

I populate the dropdown menu with the GET Request's distList.sectionName values. What I am trying to do is catch the index of the selected museum and then send this index's values to the another API call. For example; lets say user is select the "İnternet Müzesi" in the dropdown menu. After that I need to locate the position of the "İnternet Müzesi" in the distList. And then catch this two fields: "distId": "MRK" and "sectionId": "INT01" values so I can send these values to another API call. How can I achieve this?
My DropdownButton widget:
Container(
child: DropdownButton<String>(
hint: Text("Lütfen listeden seçim yapın."),
items: snapshot.data.distList
.map<DropdownMenuItem<String>>((item) {
return DropdownMenuItem<String>(
value: item.sectionName,
child: Text(item.sectionName));
}).toList(),
value: _currentSelectedValue,
isExpanded: false,
onChanged: (String? value) {
print("Drop Down Selected Museum is $value");
setState(() {
_currentSelectedValue = value;
});
},
),
),
Here is my GET Request response:
"distList": [
{
"distId": "MRK",
"sectionId": "INT01",
"sectionName": "İnternet Müzesi",
"sectionNameEng": null
},
{
"distId": "IAR",
"sectionId": "IAR01",
"sectionName": "İstanbul Arkeoloji Müzesi",
"sectionNameEng": "İSTANBUL ARCHAEOLOGICAL MUSEUMS"
},
{
"distId": "TPK",
"sectionId": "TPK01",
"sectionName": "İstanbul Topkapı Sarayı Müzesi",
"sectionNameEng": "TOPKAPI PALACE MUSEUM"
},
{
"distId": "MRK",
"sectionId": "CUM01",
"sectionName": "Ankara Cumhuriyet Müzesi",
"sectionNameEng": "MUSEUM OF REPUBLIC OF ANKARA"
}
],
"acknowledge": true,
"message": null,
"requestId": null
}

ok, I found the solution.
in the setState I catch the selectedValue's field like this:
_currentSelectedValue = value;
var var2 = snapshot.data.distList!.firstWhere(
(e) =>
e.sectionName ==
"$_currentSelectedValue");
print(var2.distId);
print(var2.sectionId);
});

Related

add label in dropdown item but MUST depends other variable (FLUTTER)

List<Map<String, dynamic>> category = [
{
"name": "One",
"detail": ['11', '12', '13', '14'],
"department": "aaa",
},
{
"name": "two",
"detail": ['21', '22', '23', '24'],
"department": "bbb",
},
{
"name": "three",
"detail": ['31', '32', '33', '34'],
"department": "ccc",
},
{
"name": "four",
"detail": ['41', '42', '43', '44'],
"department": "aaa",
},
{
"name": "five",
"detail": ['41', '42', '43', '44'],
"department": "aaa",
},
];
for (final item in category) {
if (item["department"] == "aaa") {
for (final value in item.values) {
if (value is List) {
for (final listValue in value) {
data.add({'value': listValue, 'bold': false});
}
} else {
data.add({'value': item['department'], 'bold': true});
}
}
}
}
I have used the above (loop) method to doing the dropdown, but the category "name" will repeat many times, as shown in first picture
May I know how to make the list category be like the second picture dropdown, for example, the name will be the label, detail will be item of the label. Lastly, the 'department' is for classify showing which data, let say I want to show the data that department is 'aaa' means that 3 list data will be shown in the dropdown item.
Looking at your data named as "category" which is a list of Maps, I think you can add labels and achieve the required functionality that includes using custom variable in the following way:
const dept = 'aaa';
final data = category.where((element) => element['department'] == dept);
List<DropdownMenuItem<String>>? get_items() {
final List<DropdownMenuItem<String>> _dropdownItems1 = [];
for (final val in data) {
for (final value in val.values) {
if (value is List) {
for (final listValue in value) {
_dropdownItems1.add(
DropdownMenuItem(
child: Text(listValue),
value: listValue,
),
);
}
} else if (value != dept) {
_dropdownItems1.add(DropdownMenuItem(
child:
Text(value, style: const TextStyle(fontWeight: FontWeight.bold)),
value: value,
));
}
}
}
return _dropdownItems1;
}
Now, in the dropdownbutton you can simply call "get_items()" to get the dropdown menu items for creating the dropdown menu.
It can be done as mentioned in the code below.
DropdownButton<String>(
value: selectedItem,
items: get_items(),
onChanged: (value) {
setState(() {
selectedItem = value;
});
}),
The output will be as follows:
Output Dropdown menu

Can't create DropdownButton with List of objects in Flutter

This is the error I have got:
Here is my DropdownButton code:
DropdownButton countryPicker() {
return DropdownButton<String>(
onChanged: (value) {
setState(() {
country = value;
});
},
value: country,
hint: Text(country),
items: countries(),
);
}
List<DropdownMenuItem<String>> countries() {
List<DropdownMenuItem<String>> list = [];
countryDetails.forEach((c) {
list.add(DropdownMenuItem<String>(
child: Text(c.countryName),
value: c.countryName,
));
});
return list;
}
All of my data list is in countryDetails variable.
And the list is like this:
[
{
"country_name": "Andorra",
"alpha2_code": "AD",
"states": [
{"state_name": "Andorra la Vella"},
{"state_name": "Canillo"},
]
},
..............
..............
]
So, whats the problem here?
In the error it says you have two or more DropdownMenuItem with the same value, which is not allowed.
When I take a look at your code, it seems like you are passing c.countryName as the value, but could you double check and make sure that all of your country_name are unique?

Flutter app with loading while retrieving API

I'm using an API which returns the value like this.
[
{
"store": "AMAZON"
},
{
"store": "FLIPKART"
},
{
"store": "WALMART"
},
{
"store": "ALIBABA"
},
]
I need this to be in a drop down.
I need a drop down button with this API data in it. Some one help please. I have tried many ways but nothing worked.
nigale try code:
List<String> markets = []; // Or var markets = [];
String _mySelection;
#override
void initState() {
buidDropDownItems();
super.initState();
}
//
void buidDropDownItems() async {
markets = await retrievedata.getMarket();
// Refresh the UI if the State object has been created
if(mounted){
setState(() {});
}
}
child: DropdownButton(
items: markets.map<DropdownMenuItem<String>>((String val){
return DropdownMenuItem<String>(value: val, child: Text(val));
}).toList(), // Get items from the available data in markets variable
onChanged: (sto) {
setState(() {
_mySelection = sto;
});
},
value: _mySelection,
hint: Text('Please select the store: '),
),
The function retrievedata.getMarket(); is returning Future<dynamic> which dynamic is your markets list.
let's say that this array is retrieved in a variable called data
List<String>list=[];
for(var itemData in data){
list.add(itemData['store']);
}
And wala, Now list conation array of String ready to be used

How can i Filter a Json list in Flutter

i'm trying to create a dependable dropdown in flutter using json.
I have this json list in my code
List<Map> myJson = [
{"id": 0, "continent": "Africa", "country":"Egypt"},
{"id": 1, "continent": "Europe", "country":"Denmark"},
{"id": 2, "continent": "Asia", "country":"India"},
{"id": 3, "continent": "Africa", "country":"Kenya"},
{"id": 4, "continent": "Europe", "country":"Spain"},
];
And i am showing the continent in a drop down
DropdownButton<String>(
isExpanded: true,
isDense: true,
hint: new Text("Select"),
value: _mySelection,
onChanged: (String newValue) {
setState(() {
_mySelection = newValue;
});
print(_mySelection);
},
items: myJson.map((Map val) {
return new DropdownMenuItem<String>(
value: val["continent"].toString(),
child: Text(
val["continent"],
),
);
}).toList(),
),
The above code does not work. any time i run it i get this error on the console.
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 285 pos 10: 'data != null'
I want to show a list of African countries and populate it in another Dropdown(e.g country dropdown) if a select Africa from the current drop down. i have search for solutions but most of the solutions on Stack overflow are not related to my situation. thanks in advance.
hopefully you are looking for something like this
you can groupBy your List, then you have only distinct continents
collection.dart is required
import "package:collection/collection.dart";
var newMap = groupBy(myJson, (obj) => obj['continent']);
in the new Map the key is your groupBy Field, you can do it the same for the countrys
items: newMap.entries.map((val) {
return new DropdownMenuItem<String>(
value: val.key.toString(),
child: Text(
val.key,
),
);
}).toList(),

The argument type 'List<Iterable<DropdownMenuItem<int>>>' can't be assigned to the parameter type 'List<DropdownMenuItem<dynamic>>'

In flutter I'm using TMDB API and getting genre names from there and want to display them on my DropdownButton but I got this error.
The argument type List < Iterable< DropdownMenuItem< int>>> can't be assigned
to the parameter type 'List< DropdownMenuItem< dynamic>>
{
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 12,
"name": "Adventure"
},
{
"id": 16,
"name": "Animation"
}, .......]
}
this is the json.
return DropdownButton(
items: [ snapGenre.data.genres.map((map) => DropdownMenuItem(child: Text(map.name),value: map.id,))]
);
}
this part is what I have tried.
Briefly what I want to do is, I want to return/create a dropDownMenuItem according how many genre name I get from the API. Which part I miss can you help me please.
You are declaring a List by using [], and then mapping your data inside it, so you ended up with a Iterable inside a List. Instead, you must remove the [] and convert the Iterable to a List at the end:
return DropdownButton(
items: snapGenre.data.genres.map((map) => DropdownMenuItem(
child: Text(map.name),
value: map.id,
),
).toList(),
);