Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.0k views
in Technique[技术] by (71.8m points)

dart - Flutter populate dropdown button from json array

How do I populate this JSON list into dropdown button?

{
    "status": true,
    "message": "success",
    "data": {
        "list": [
            {
                "idattribute": "2",
                "attrName": "BBQ"
            },
            {
                "idattribute": "1",
                "attrName": "FRUIT JUICE"
            }
        ]
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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),
        ),
      ),
    );
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...