say*_*ank 5 json asynchronous async-await dart flutter
我一直在尝试使用 Flutter 编写这个应用程序,我想制作一个下拉按钮,用于显示由 Django 制作的 API 从 JSON 响应接收到的值。
\n\nJSON 响应如下,
\n\n[{"name": "FC1", "username": "admin"}, {"name": "FC2", "username": "admin"}]\nRun Code Online (Sandbox Code Playgroud)\n\n这是使用的对象类,
\n\nclass FoodCourt {\n final String name;\n FoodCourt(this.name);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n这是用于获取数据的方法,
\n\nFuture<List<FoodCourt>> _getFoodCourt() async {\n var data = await http\n .get("http://timetable-api-manipal.herokuapp.com/getfoodcourt");\n var jsonData = json.decode(data.body);\n\n List<FoodCourt> fcs = [];\n\n for (var u in jsonData) {\n FoodCourt fc = FoodCourt(u["name"]);\n fcs.add(fc);\n }\n print(fcs);\n return fcs;\n} \nRun Code Online (Sandbox Code Playgroud)\n\n这是我使用的 FutureBuilder Widget,
\n\nFutureBuilder(\n future: _getFoodCourt(),\n builder: (context, snapshot) {\n return DropdownButton<String>(\n hint: Text("Select"),\n value: selectedFc,\n onChanged: (newValue) {\n setState(() {\n selectedFc = newValue;\n });\n },\n items: snapshot.data.map((fc) {\n return DropdownMenuItem<String>(\n child: Text(fc.name),\n value: fc.name,\n );\n }));\n }),\nRun Code Online (Sandbox Code Playgroud)\n\n显示的错误是,
\n\nI/flutter (31862): \xe2\x95\x90\xe2\x95\x90\xe2\x95\xa1 EXCEPTION CAUGHT BY WIDGETS LIBRARY \xe2\x95\x9e\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\n\nI/flutter (31862): The following assertion was thrown building FutureBuilder<List<FoodCourt>>(dirty, state:\nI/flutter (31862): _FutureBuilderState<List<FoodCourt>>#3c097):\nI/flutter (31862): type \'MappedListIterable<FoodCourt, \nDropdownMenuItem<FoodCourt>>\' is not a subtype of type\nI/flutter (31862): \'List<DropdownMenuItem<FoodCourt>>\'\nRun Code Online (Sandbox Code Playgroud)\n\n我一直在尝试许多不同的方法来解决这个问题,而这个似乎对我来说最有意义,但它不起作用。\n如果有人可以输入示例代码,那将会有很大帮助。工作解决方案!
\n你必须根据@saed的回答首先设置两件事
items: snapshot.data.map((fc) =>
DropdownMenuItem<String>(
child: Text(fc.name),
value: fc.name,
)
).toList();
Run Code Online (Sandbox Code Playgroud)
和设置类型的第二件事,FutureBuilder例如
FutureBuilder<List<FoodCourt>>(..... Your code
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11666 次 |
| 最近记录: |