Flutter DropdownButton - populate items from rest webservice Flutter DropdownButton - populate items from rest webservice flutter flutter

Flutter DropdownButton - populate items from rest webservice


You should not use FutureBuilder for this situation. Rather fetch the data in initState() and then cause a rebuild using setState() to update the view.

If fetchCities() creates a new Future every time it is called, then build() will invoke that fetch every time the UI is rebuilt (which can be quite often)

https://docs.flutter.io/flutter/widgets/FutureBuilder-class.html

The future must have been obtained earlier, e.g. during State.initState, ...


      child: FutureBuilder(            future: Webservice().load(Country.countries) ,            builder: (context, snapshot){              if(snapshot.hasError)                return Text(snapshot.error);              if (snapshot.hasData) {                return  DropdownButtonFormField(                  decoration: new InputDecoration(icon: Icon(Icons.language)), //, color: Colors.white10                  value: selectedCountry,                  items: snapshot.data.map<DropdownMenuItem<Country>>((Country country) {                       return  DropdownMenuItem<Country>(                                value: country,                                child: Text(country.name, style: TextStyle(color: Color.fromRGBO(58, 66, 46, .9))),                              );                  })                          .toList(),                  onChanged: (Country newValue) {                      setState(() => selectedCountry = newValue);                      // selectedCountry = newValue;                      print(newValue.id);                      print(newValue.name);                  },               );              }              return CircularProgressIndicator();


I had the same issue today, and after some digging, I found a mistake in my code: the value in the DropdownButton wasn't in the items list.

I assumed (wrongly) that the dropdown would handle the "empty" value - but that is not the case.