简体   繁体   中英

Flutter DropDownButton using FutureBuilder for JSON Response

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!

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();

You have to set tow 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM