Toujo
Toujo

Reputation: 335

How to implement DropdownList with JSON data

I need to display list of PartnerName in the dropdown list and when I click PartnerName it need to go to respective Test of that PartnerName.

For now only I'm getting all the partner name in my console. How to display them in my dropdownList and the depending dropdown?

My API function:

    Future<List<Partner>> AllPathLab() async {
    var jsonResponse;
  
      var response = await http.post(Uri.parse("http://MyUrlhssjsjjsd),
          body: ({
            
          }));
      if (response.statusCode == 200) {
        jsonResponse = json.decode(response.body.toString());
        print(jsonResponse);

        AllPathLabTestModel dataModel = allPathLabTestModelFromJson(response.body);
        print(dataModel.partner.length);
        for (final item in dataModel.partner) 
        print(item.partnerName);

        List<Partner> arrData = dataModel.partner; // this "partner" is actual json array of data[]
        return arrData;
      } else {
        print("Wrong URL");
        throw Exception("Faild to fetch");
      }
    
  }

My Json response for all partner:

{
"Status": "1",
"Message": "",
"Partner": [
    {
        "EncPartnerId": "gtetetetetet",
        "PartnerName": "tetetet"
    },
    {
        "EncPartnerId": "tettet",
        "PartnerName": "tetette"
    },
     ]
}

Full code: For now my dropdown displaying the dummy data Im trying to replace them with my Json data

 class _MultipleTestBookingState extends State<MultipleTestBooking> {


  void initState(){
  super.initState();
  AllPathLab();
}



  String _selectedDate = DateTime.now().toString();
  final List<String> allLabList = [
    "Select Lab",
    "Abc",
    "Xyz",
  ];
  String selectedLabFromList = "Abc";

  @override
  Widget build(BuildContext context) {
    var screenWidth = MediaQuery.of(context).size.width;
    var screenHeight = MediaQuery.of(context).size.height;
    var blockSizeHorizontal = (screenWidth / 100);
    var blockSizeVertical = (screenHeight / 100);

    return Scaffold(
      body: SafeArea(
        child: Container(
          child: Column(
            children: [
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: ListTile(
                  title: Text("Booking Information",
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: blockSizeHorizontal * 5,
                        fontFamily: 'Poppins',
                        color: Theme.of(context).primaryColor,
                      )),
                  subtitle: Text("Preferred Visit Date"),
                ),
              ),
              //==============================================================================
              Container(
                margin: EdgeInsets.only(left: 20),
                padding: EdgeInsets.only(left: 0, right: 150),
                decoration: BoxDecoration(
                  color: Colors.lightBlue[50],
                  borderRadius: BorderRadius.all(Radius.circular(12)),
                  ,
                ),
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: DateTimePicker(
                    initialValue: DateTime.now().toString(),
                    type: DateTimePickerType.date,
                    dateLabelText: 'Select Date',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: blockSizeHorizontal * 3.5,
                      fontFamily: 'Poppins',
                      color: Colors.green,
                      letterSpacing: 2.0,
                    ),
                    firstDate: DateTime.now(),
                    lastDate: DateTime.now().add(Duration(
                        days: 30)), // This will add one year from current date
                    validator: (value) {
                      return null;
                    },
                    onChanged: (value) {
                      if (value.isNotEmpty) {
                        setState(() {
                          _selectedDate = value;
                        });
                      }
                    },
                    onSaved: (value) {
                      if (value.isNotEmpty) {
                        _selectedDate = value;
                      }
                    },
                  ),
                ),
              ),

              //==============================================================================

              ListTile(
                title: Text(
                  " Select Pathological Lab",
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: blockSizeHorizontal * 4.0,
                    fontFamily: 'Poppins',
                    color: Theme.of(context).primaryColor,
                  ),
                ),
              ),

              Padding(
                      padding: const EdgeInsets.only(left: 0.0),
                      child: DropdownButton<String>(
                        style: TextStyle(
                          color: Colors.green,
                          fontSize: 15,
                          fontFamily: 'Poppins',
                        ),
                        value: selectedLabFromList,
                        onChanged: (value) {
                          setState(() {
                            selectedLabFromList = value!;
                          });
                        },
                        items:allLabList.map<DropdownMenuItem<String>>((value) {
                          return DropdownMenuItem(
                            child: Text(value),
                            value: value,
                          );
                        }).toList(),
                      ),
                    ),
            ],
          ),
        ),
      ),
    );
  }

Upvotes: 0

Views: 186

Answers (1)

Jahidul Islam
Jahidul Islam

Reputation: 12575

Edited you can try with the Future builder

FutureBuilder<List<Partner>>

and your items

Container(
                      child: FutureBuilder<List<Partner>>(
                        future: AllPathLab(),
                        builder:
                            (BuildContext context, AsyncSnapshot snapshot) {
                          if (snapshot.connectionState !=ConnectionState.done) {
                            return CircularProgressIndicator();
                          }
                          if (snapshot.hasError) {
                            return Text("Somthing went wrong");
                          }

                          if (snapshot.hasData) {
                            return DropdownButton<Partner>(
                      dropdownColor: Colors.white,
                      underline: SizedBox(),
                      isExpanded: true,
                      items: snapshot.data.map((Partner data) =>
                                               DropdownMenuItem<Partner>(
                                                 child: Text(data.PartnerName),
                                                 value: data,
                                               )
                                              ).toList(),
                              onChanged: (value) {
                              });
                          },
                              );
                          }
                          return Text("Waiting for Internet Connection");
                        },
                      ),
                    ),

Upvotes: 1

Related Questions