Home > database >  how to solve this response type '({bool growable}) => List<DropdownMenuItem<dynamic>
how to solve this response type '({bool growable}) => List<DropdownMenuItem<dynamic>

Time:11-09

I tried to retrieve data from the API to display in the dropdown but an error occurred, I've tried according to what I was looking for on google and also the forum but the problem still appears. is there something wrong in writing in my code, Thank you

this is the function that is executed when calling the api and the response is 200.

class UtilFunction {
  String? _valMenu;
  var _dataMenu = [];

  Future getSemester() async {
    String url = Constant.baseURL;
    String token = await UtilSharedPreferences.getToken();
    final respose = await http.get(
      Uri.parse(
        '$url/auth/semester/get_smt',
      ),
      headers: {
        'Authorization': 'Bearer $token',
      },
    );
    await http
        .get(
          Uri.parse(
            '$url/auth/semester/get_smt',
          ),
        )
        .then((value) => (() {
              // respose = value; //untuk melakukan request ke webservice
              var listData =
                  jsonDecode(respose.body); //lalu kita decode hasil datanya
              _dataMenu = listData['data'];
              _valMenu = _dataMenu[0]['data'];
            }));
    print(respose.statusCode);
    print(respose.body);
    return _dataMenu;
  }
}

and I take the above function here.

Container(
                child: FutureBuilder(
                  future: UtilFunction().getSemester(),
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      return Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          DropdownButtonFormField(
                            value: _valMenu,
                            onChanged: (value) {},
                            items: snapshot.data
                                .map<DropdownMenuItem>(
                                    (project) => DropdownMenuItem(
                                          value: project['smt'],
                                          child: Text(project['smt']),
                                        ))
                                .toList,
                          ), ...

this response json

{
    "status": "success",
    "code": "200",
    "data": [
        {
            "id": "254dd6e9-791e-4a2b-959e-6ec5929f3104",
            "id_ta": "2b4d2dd1-ef8e-461b-b7c3-48409a13969e",
            "ta": "2022-2023",
            "smt": "GANJIL",
            "semester": "2022-2023 GANJIL",
            "periode_awal": "Senin, 01 Agustus 2022",
            "periode_akhir": "Minggu, 22 Januari 2023",
            "p_awal": "2022-08-01",
            "p_akhir": "2023-01-22",
            "period_smt": "Senin, 01 Agustus 2022 - Minggu, 22 Januari 2023",
            "created_at": "2022-08-10 05:02:18",
            "updated_at": "2022-09-06 03:57:00",
            "created_by": "Superadmin",
            "updated_by": "Dasep",
            "sts_hapus": 1
        }
    ]
}

CodePudding user response:

Change List<DropdownMenuItem> to List<DropdownMenuItem<String>>

                        snapshot.data
                                .map<DropdownMenuItem<String>>(
                                    (project) => DropdownMenuItem<String>(
                                          value: project['smt'],
                                          child: Text(project['smt']),
                                        ))
                                .toList()

Also In the decoding try this

             var listData =  jsonDecode(respose.body);  as Map<String, dynamic>
             if(listData.containsKey('data')){
                   _dataMenu = listData['data'];
                  _valMenu = _dataMenu[0]['data']; 
               } else {
                 // HANDLE NO DATA SCENARIO
               } 
}

CodePudding user response:

there are some problems with you get data and how you print it. I have used public api you can change the url.

class UtilFunction {
  String? _valMenu;
  List<String> _dataMenu = [];

  Future getSemester() async {
    await http.get(Uri.parse("http://universities.hipolabs.com/search?country=United States")).then((value) {
      // respose = value; //untuk melakukan request ke webservice
      var listData = jsonDecode(value.body); //lalu kita decode hasil datanya
      for (var i = 0; i < 10; i  ) {
        _dataMenu.add(listData[i]["domains"][0]);
      }
      _valMenu = _dataMenu[0];
    });
    return _dataMenu;
  }
}

Also I have made some changes in FutureBuilder. Note that you will also need to change return type of your api call to give first element of the dropdown value.

FutureBuilder(
                future: UtilFunction().getSemester(),
                builder: (context, AsyncSnapshot snapshot) {
                  if (snapshot.hasData) {
                    val = snapshot.data[0];
             
                    return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
    
                      DropdownButton<String>(
                        value: val,
                        onChanged: (value) {
                          val = value!;
                        },
                        items: snapshot.data
                            .map<DropdownMenuItem<String>>((String project) => DropdownMenuItem<String>(
                                  value: project,
                                  child: Text(project),
                                ))
                            .toList(),
                      ),
                    ]);
                  } else {
                    return Text("dsds");
                  }
                })
  • Related