Flutter从JSON数组填充下拉按钮

时间:2019-09-09 03:59:05

标签: flutter dart

如何将该JSON列表填充到下拉按钮中?

{
    "status": true,
    "message": "success",
    "data": {
        "list": [
            {
                "idattribute": "2",
                "attrName": "BBQ"
            },
            {
                "idattribute": "1",
                "attrName": "FRUIT JUICE"
            }
        ]
    }
}

1 个答案:

答案 0 :(得分:3)

enter image description here

class _YourPageState extends State<YourPage> {
  Map yourJson = {
    "status": true,
    "message": "success",
    "data": {
      "list": [
        {"idattribute": "2", "attrName": "BBQ"},
        {"idattribute": "1", "attrName": "FRUIT JUICE"}
      ]
    }
  };
  int _value = 1;
  List<DropdownMenuItem<int>> _menuItems;

  @override
  void initState() {
    super.initState();

    List dataList = yourJson["data"]["list"];
    _menuItems = List.generate(
      dataList.length,
          (i) => DropdownMenuItem(
        value: int.parse(dataList[i]["idattribute"]),
        child: Text("${dataList[i]["attrName"]}"),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: DropdownButton<int>(
          items: _menuItems,
          value: _value,
          onChanged: (value) => setState(() => _value = value),
        ),
      ),
    );
  }
}