【问题标题】:How to filter JSON data in itemBuilder如何在 itemBuilder 中过滤 JSON 数据
【发布时间】:2019-08-17 00:39:36
【问题描述】:

所以我有一个 JSON url,其中包含一些数据,如名称、纬度和经度。但是,并非每个对象都有纬度和经度,我只想显示具有纬度和经度的对象的名称。

带有 lat 和 lng 的 JSON 示例对象:

    dynamicDataUrl: "http://example.com",
    staticDataUrl: "http://example.com",
    limitedAccess: false,
    locationForDisplay: {
        coordinatesType: "LA4556",
        latitude: 52.2490470982696,
        longitude: 6.16317987442017
    },
    identifier: "4556random2595",
    name: "Los Angelos"
    },

没有 lat 和 lng 的 JSON 示例对象:

    dynamicDataUrl: 
"http://example.com",
    staticDataUrl: "https://example.com",
    limitedAccess: false,
    identifier: "1234randomi1233",
    name: "New York"
},
List data;
Future<String> theRequest() async {
    var response = await http.get(Uri.encodeFull(url),
    headers: {
      'Accept': 'application/json'
    });

    setState(() {

      var getRequestedData = jsonDecode(response.body);
      data = getRequestedData['parkingFacilities'];

    });
  }

  @override
  void initState() {
    this.theRequest();
  }

  @override
  Widget build(BuildContext context) {
    bool notNull = false;
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Parking Spots'),
      ),
      body: new ListView.builder(
        itemCount: data == null ? 0 : data.length,
        itemBuilder: (BuildContext context, i) {
          if( data[i]['locationForDisplay'] != null ) {
            return new ListTile(
              title:  new Text(data[i]['name']), 
              trailing: new Icon(
                saved ? Icons.favorite : Icons.favorite_border,
                color: saved ? Colors.red : null,
              ),
              onTap: (){_save(data[i]['name'], data[i]['locationForDisplay']['latitude'], data[i]['locationForDisplay']['longitude']);},
            );
          }
        },
      )
    );
  }

我在 itemBuilder 中尝试过的代码只显示一个对象名称。我还尝试使用 forloop 在setState() 函数内部进行过滤,它确实在我打印它时返回了我需要的数据(只有来自具有 lat 和 lng 的对象的对象名称),但是当我尝试将 data[i]['name'] 设置为 ListTile 的标题,我仍然看到所有名称。

如何正确过滤 JSON,以便只显示具有 lat 和 lng 的对象的名称?

【问题讨论】:

  • 这是因为您returning 在第一个具有“locationForDisplay”的对象上,而不是过滤掉对象并返回过滤后的列表

标签: json dart flutter


【解决方案1】:

您可以创建一个List 变量并过滤值,如下所示:

  List data;
  List<Map> filteredList;


  Future<String> theRequest() async {
      var response = await http.get(Uri.encodeFull(url),
      headers: {
        'Accept': 'application/json'
      });

      setState(() {

        var getRequestedData = jsonDecode(response.body);
        data = getRequestedData['parkingFacilities'];

        filteredList = List();
        for(item in data){
          if (item['locationForDisplay'] != null && item['locationForDisplay']['latitude'] != null && item['locationForDisplay']['longitude'] != null
          ) {
            filteredList.add(item);
          }
        }

      });
    }

    @override
    void initState() {
      this.theRequest();
    }

    @override
    Widget build(BuildContext context) {
      bool notNull = false;
      return new Scaffold(
        appBar: new AppBar(
          title: new Text('Parking Spots'),
        ),
        body: new ListView.builder(
          itemCount: filteredList == null ? 0 : filteredList.length,
          itemBuilder: (BuildContext context, i) {
              return new ListTile(
                title:  new Text(filteredList[i]['name']), 
                trailing: new Icon(
                  saved ? Icons.favorite : Icons.favorite_border,
                  color: saved ? Colors.red : null,
                ),
                onTap: (){_save(filteredList[i]['name'], filteredList[i]['locationForDisplay']['latitude'], filteredList[i]['locationForDisplay']['longitude']);},
              );

          },
        )
      );
    }

【讨论】:

  • filteredData == null ? 0 : filteredData.length 添加到 itemCount,为我解决了这个问题。谢谢!
【解决方案2】:

data 大概是List&lt;Map&lt;String, dynamic&gt;&gt;,所以你可以添加:

  data = getRequestedData['parkingFacilities'];
  data.removeWhere((m) => m['locationForDisplay'] == null);

【讨论】:

  • data 的类型为 List,但我将其更改为 List&lt;Map&lt;String, dynamic&gt;&gt; data 并粘贴了新行,现在它给了我这个例外:Unhandled Exception: type 'List&lt;dynamic&gt;' is not a subtype of type 'List&lt;Map&lt;String, dynamic&gt;&gt;'
  • 只需从谓词中删除类型,并将数据保留为List - 查看更新的答案
猜你喜欢
  • 2020-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-02
  • 2020-03-26
  • 2018-01-24
相关资源
最近更新 更多