如何在itemBuilder中过滤JSON数据

时间:2019-03-26 15:05:24

标签: json dart flutter

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

带有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,以便只显示确实包含经纬度和经度的对象的名称?

2 个答案:

答案 0 :(得分: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']);},
              );

          },
        )
      );
    }

答案 1 :(得分:1)

data大概是List<Map<String, dynamic>>,因此您可以添加:

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