Reputation: 129
I've been trying to code this app using Flutter and I want to make a Dropdown Button which displays the values received from a JSON response by an API made with Django.
The JSON response is as follows,
[{"name": "FC1", "username": "admin"}, {"name": "FC2", "username": "admin"}]
This is the Object class used,
class FoodCourt {
final String name;
FoodCourt(this.name);
}
This is the method used to GET the data,
Future<List<FoodCourt>> _getFoodCourt() async {
var data = await http
.get("http://timetable-api-manipal.herokuapp.com/getfoodcourt");
var jsonData = json.decode(data.body);
List<FoodCourt> fcs = [];
for (var u in jsonData) {
FoodCourt fc = FoodCourt(u["name"]);
fcs.add(fc);
}
print(fcs);
return fcs;
}
and this is the FutureBuilder Widget I used,
FutureBuilder(
future: _getFoodCourt(),
builder: (context, snapshot) {
return DropdownButton<String>(
hint: Text("Select"),
value: selectedFc,
onChanged: (newValue) {
setState(() {
selectedFc = newValue;
});
},
items: snapshot.data.map((fc) {
return DropdownMenuItem<String>(
child: Text(fc.name),
value: fc.name,
);
}));
}),
The error shown is,
I/flutter (31862): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (31862): The following assertion was thrown building FutureBuilder<List<FoodCourt>>(dirty, state:
I/flutter (31862): _FutureBuilderState<List<FoodCourt>>#3c097):
I/flutter (31862): type 'MappedListIterable<FoodCourt,
DropdownMenuItem<FoodCourt>>' is not a subtype of type
I/flutter (31862): 'List<DropdownMenuItem<FoodCourt>>'
I've been trying many different ways to solve this problem, and this one seemed to make the most sense for me and yet it's not working. Would be of great help if someone could type in a sample code for a working solution!
Upvotes: 6
Views: 12377
Reputation: 47059
You have to set two things first as per @saed's answer
items: snapshot.data.map((fc) =>
DropdownMenuItem<String>(
child: Text(fc.name),
value: fc.name,
)
).toList();
and Second thing at FutureBuilder
set type like
FutureBuilder<List<FoodCourt>>(..... Your code
Upvotes: 6
Reputation: 6861
Your items is not a list use this code instead :
items: snapshot.data.map((fc) =>
DropdownMenuItem<String>(
child: Text(fc.name),
value: fc.name,
)
).toList();
Upvotes: 3