【问题标题】:How to find the length of the JSON in flutter如何在flutter中找到JSON的长度
【发布时间】:2020-11-18 05:20:14
【问题描述】:

我使用 API 作为返回 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 flutter dart dropdown


【解决方案1】:

你可以这样得到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: (_) {},
)

【讨论】:

    【解决方案2】:

    您始终可以通过将 JSON 对象传递给映射来找到它的长度,

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

    让我知道这是否有效。

    【讨论】:

      【解决方案3】:

      将你的json解码为stores后,你的stores是一个json对象的列表,所以现在你可以像这样简单地获取stores的长度。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-10
        • 1970-01-01
        • 2021-05-12
        • 2021-07-01
        • 2010-12-06
        • 2010-09-20
        相关资源
        最近更新 更多