Flutter DropDownButton使用FutureBuilder进行JSON响应

时间:2019-06-29 06:40:15

标签: json asynchronous flutter dart async-await

我一直在尝试使用Flutter编写该应用程序,我想创建一个下拉按钮,以显示由Django制作的API从JSON响应接收的值。

JSON响应如下,

[{"name": "FC1", "username": "admin"}, {"name": "FC2", "username": "admin"}]

这是使用的Object类,

class FoodCourt {
  final String name;
  FoodCourt(this.name);
}

这是用于获取数据的方法,

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;
} 

这是我使用的FutureBuilder小部件,

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,
                  );
                }));
          }),

显示的错误是

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>>'

我一直在尝试许多不同的方法来解决此问题,这种方法对我来说似乎最有意义,但是它没有用。 如果有人可以输入示例代码来找到有效的解决方案,那将有很大的帮助!

2 个答案:

答案 0 :(得分:2)

您的项目不是列表,请改用此代码:

items: snapshot.data.map((fc) =>
       DropdownMenuItem<String>(
        child: Text(fc.name),
        value: fc.name,
      )
    ).toList();

答案 1 :(得分:2)

您必须先按照 @saed的答案

设置拖车
items: snapshot.data.map((fc) =>
       DropdownMenuItem<String>(
        child: Text(fc.name),
        value: fc.name,
      )
    ).toList();

FutureBuilder的第二件事设置为

FutureBuilder<List<FoodCourt>>(..... Your code