0

I am trying to show a data in dropdown menu,but i have a weird problem i can't seem to figure it out.The problem is when open the view that contained dropdown menu the api data fetch data from server,it work as excepted but the data not shows to the dropdown for first time,in debug mode when i press hot realod the data is shown to dropdown menu not when the view shows first time

Dropdown menu

                  Flexible(
                    flex: 0,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Container(
                        height: 45,
                        width: 300,
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(5),
                            border: Border.all(
                                color: Color.fromRGBO(92, 52, 76, 1))),
                        child: DropdownButton<String>(
                            isExpanded: true,
                            itemHeight: 50,
                            underline: SizedBox(),
                            value: _selectedVehicle,
                            items: vehicle_list.map((vehicle) {
                              return DropdownMenuItem<String>(
                                value: vehicle.id,
                                child: new Text(
                                  vehicle.model,
                                  style: TextStyle(
                                      fontSize: 15,
                                      color: Color.fromRGBO(
                                          92, 52, 76, 1)),
                                ),
                              );
                            }).toList(),
                            hint: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Text("Please Select Vehicle"),
                            ),
                            onChanged: (newValues) {
                              setState(() {
                                _selectedVehicle = newValues;
                              });
                            }),
                      ),
                    ),
                  )

API

Future<String> getVehicles() async {
    vehicle_list.clear();
    Future tokens = SharedPrefrence().getToken();
    tokens.then((data) async{
      token=data;
      var response = await http.get(Urls.BASE_URL + Urls.GET_VEHICLES, headers: {
        "Authorization": "Bearer " + token,
        "Content-Type": "application/json"
      });
      if (response.statusCode == 200) {
        print("vechiles " + response.body.toString());
        Map<String, dynamic> value = json.decode(response.body);
        try {
          var data = value['data'];
          for (int i = 0; i < data.length; i++) {
            var obj = data[i];
            vehicle_list.add(VehicleModel(
                obj['id'].toString(),
                obj['user_id'].toString(),
                obj['type'].toString(),
                obj['model'],
                obj['reg_no'],
                obj['fuel_type'].toString()));
          }
        } catch (e) {
          
          print(e.toString());
        }
      } else {
        print(response.body.toString());
      }
    });
  }

intilization

List<VehicleModel> vehicle_list = [];
String _selectedVehicle;

This how i call the function

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getVehicles();
   
  }

2 Answers 2

1

I think this will resolve your issue:

Future<String> getVehicles() async {
    vehicle_list.clear();
    Future tokens = SharedPrefrence().getToken();
    tokens.then((data) async{
      token=data;
      var response = await http.get(Urls.BASE_URL + Urls.GET_VEHICLES, headers: {
        "Authorization": "Bearer " + token,
        "Content-Type": "application/json"
      });
      if (response.statusCode == 200) {
        print("vechiles " + response.body.toString());
        Map<String, dynamic> value = json.decode(response.body);
        try {
          var data = value['data'];
          for (int i = 0; i < data.length; i++) {
            var obj = data[i];
            vehicle_list.add(VehicleModel(
                obj['id'].toString(),
                obj['user_id'].toString(),
                obj['type'].toString(),
                obj['model'],
                obj['reg_no'],
                obj['fuel_type'].toString()));
          }
          
          // add this line...
          WidgetsBinding.instance.addPostFrameCallback((_) => setState((){}));
        } catch (e) {
          
          print(e.toString());
        }
      } else {
        print(response.body.toString());
      }
    });
  }
Sign up to request clarification or add additional context in comments.

Comments

1

You have call setState at the end of the function to modify the state!
Something like this,

Future<String> getVehicles() async {
    vehicle_list.clear();
    Future tokens = SharedPrefrence().getToken();
    tokens.then((data) async{
      token=data;
      var response = await http.get(Urls.BASE_URL + Urls.GET_VEHICLES, headers: {
        "Authorization": "Bearer " + token,
        "Content-Type": "application/json"
      });
      if (response.statusCode == 200) {
        print("vechiles " + response.body.toString());
        Map<String, dynamic> value = json.decode(response.body);
        try {
          var data = value['data'];
          for (int i = 0; i < data.length; i++) {
            var obj = data[i];
            vehicle_list.add(VehicleModel(
                obj['id'].toString(),
                obj['user_id'].toString(),
                obj['type'].toString(),
                obj['model'],
                obj['reg_no'],
                obj['fuel_type'].toString()));
          }
          setState(() {});
        } catch (e) {
          
          print(e.toString());
        }
      } else {
        print(response.body.toString());
      }
    });
  }

Hope that works!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.