【问题标题】:Flutter DropDownButton using FutureBuilder for JSON ResponseFlutter DropDownButton 使用 FutureBuilder 进行 JSON 响应
【发布时间】: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


【解决方案1】:

您必须首先根据 @saed's 的回答设置两件事

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

第二件事 FutureBuilder 设置类型像

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      • 2018-08-28
      • 2018-03-19
      相关资源
      最近更新 更多