繁体   English   中英

Flutter DropDownButton使用FutureBuilder进行JSON响应

[英]Flutter DropDownButton using FutureBuilder for JSON Response

我一直在尝试使用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>>'

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

您的商品不是列表,请改用以下代码:

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

您必须先按照@saed的答案设置拖曳的东西

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

FutureBuilder第二件事是设置类型

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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