簡體   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