简体   繁体   中英

Populate dropdownbutton2 with data from json array in flutter

How can I populate data for dropdownbutton2 with data from a json array here is a sample of the json in flutter

"data": [
        {
            "id": "1",
            "name": "Floral"
        },
        {
            "id": "4",
            "name": "Marigold"
        },
        {
            "id": "104",
            "name": "Tulip"
        }
    ]

How can i get the values of name to be displayed in the dropdown selection but the id will be selected in the onchange function

List dataList = [];

setState(() {
      dataList = jsonData;
    });

items: dataList
                      .map((item) => DropdownMenuItem<String>(
                            value: item,
                            child: Text(
                              item['name'],
                              style: const TextStyle(
                                fontSize: 14,
                                color: Colors.black,
                              ),
                              overflow: TextOverflow.ellipsis,
                            ),
                          ))
                      .toList(),
                  onChanged: (value) {
                    item['id'],
                 }),
``

Parse items from json

final json = """{
  "data": [
        {
            "id": "1",
            "name": "Floral"
        },
        {
            "id": "4",
            "name": "Marigold"
        },
        {
            "id": "104",
            "name": "Tulip"
        }
    ]
}""";

final List<String> items = jsonDecode(json)['data'].map((i) => i['name']).toList().cast<String>();

and follow Simple DropdownButton2 example.

Example: https://pub.dev/packages/dropdown_button2

 final String data =
  '[{"ID": 1, "Code": "01", "Description": "REGION I (ILOCOS REGION)", "PSGCCode": "010000000"}, {"ID": 2, "Code": "02", "Description": "REGION II (CAGAYAN VALLEY)", "PSGCCode": "020000000"}]';
  List<Region> _region = [];

 int? selectedValue;
 final TextEditingController textEditingController = TextEditingController(); 

Model

class Region {

final int regionid;
final String regionDescription;

 Region ({
required this.regionid,
required this.regionDescription
 });
factory Region.fromJson(Map<String, dynamic> json) {

return Region(
    regionid: json['ID'],
    regionDescription: json['Description']

 );
}
}            

DropDwonButton2

               DropdownButtonHideUnderline(
                            child: DropdownButton2(
                              isExpanded: true,
                              hint: Text(
                                'Select option',
                                style: TextStyle(
                                  fontSize: 14,
                                  color: Theme.of(context).hintColor,
                                ),
                              ),
                              items: _region.map((Region map) {
                                return DropdownMenuItem(

                                  value: map.regionid,
                                  child: Text(map.regionDescription,
                                      style: TextStyle(color: Colors.black)),
                                );
                              })
                                  .toList(),
                              value: selectedValue,
                              onChanged: (value) {
                                setState(() {
                                  selectedValue = value as int;
                                  print(selectedValue);
                                });
                              },
                              buttonHeight: 40,
                              buttonWidth: 200,
                              itemHeight: 40,
                              dropdownMaxHeight: 200,
                              searchController: textEditingController,
                              searchInnerWidget: Padding(
                                padding: const EdgeInsets.only(
                                  top: 8,
                                  bottom: 4,
                                  right: 8,
                                  left: 8,
                                ),
                                child: TextFormField(
                                  controller: textEditingController,
                                  decoration: InputDecoration(
                                    isDense: true,
                                    contentPadding: const EdgeInsets.symmetric(
                                      horizontal: 10,
                                      vertical: 8,
                                    ),
                                    hintText: 'Search for an item...',
                                    hintStyle: const TextStyle(fontSize: 12),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(8),
                                    ),
                                  ),
                                ),
                              ),
                              searchMatchFn: (item, searchValue) {
                               // print(item.child);
                                Text txt = item.child as Text;
                               // print(searchValue);
                                return (txt.data.toString().toLowerCase().contains(searchValue.toLowerCase()));
                                
                              },
                              //This to clear the search value when you close the menu
                              onMenuStateChange: (isOpen) {
                                if (!isOpen) {
                                  textEditingController.clear();
                                }
                              },
                            ),
                          ),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM