【发布时间】:2021-09-08 16:59:57
【问题描述】:
我一直在尝试使用 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 Widget,
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>>'
我一直在尝试许多不同的方法来解决这个问题,这对我来说似乎最有意义,但它不起作用。 如果有人可以输入示例代码以获得有效的解决方案,那将是非常有帮助的!
【问题讨论】:
-
当您选择一个选项时,小部件是否会重新编译?
标签: json asynchronous flutter dart async-await