如何在 flutter 中找到 JSON 的长度

How to find the length of the JSON in flutter

我正在使用 API 作为 returns 一个 JSON 文件的支持。我需要将此 JSON 数据用于下拉按钮,使我收到的 JSON 数据在此处。

[
    {
        "store": "AMAZON"
    },
    {
        "store": "FLIPKART"
    },
    {
        "store": "WALMART"
    },
    {
        "store": "ALIBABA"
    },

]

JSON 的长度可能会不时变化。

在 Flutter 中,我用这一行解码 JSON。

stores = json.decode(response.body);
print(stores[0]['store']);

我需要知道 json 的长度才能在下拉按钮中使用这些数据。如果有其他方法可以直接使用 json 下拉菜单也建议我。

将您的 json 解码为存储后,您的存储是 json 对象的列表,因此现在您可以像这样简单地获取存储的长度。

stores = json.decode(response.body);
int len = stores.length;
print('length = $len');

你总能通过地图找到 JSON 对象的长度,

stores = json.decode(response.body);
(stores as Map<String, dynamic>).length

让我知道这是否有效。

你可以这样得到json的长度:

stores = json.decode(response.body);
final length = stores.length;

并获取要在下拉小部件中使用的项目列表:

  List<String> items = [];
  stores.forEach((s)=> items.add(s["store"]));

  new DropdownButton<String>(
  items: items.map((String value) {
    return new DropdownMenuItem<String>(
      value: value,
      child: new Text(value),
    );
  }).toList(),
  onChanged: (_) {},
)