json - 如何在 itemBuilder 中过滤 JSON 数据

标签 json dart flutter

所以我有一个 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"
    },

没有纬度和经度的 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,以便仅显示具有经纬度的对象的名称?

最佳答案

您可以创建一个 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']);},
              );

          },
        )
      );
    }

关于json - 如何在 itemBuilder 中过滤 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55360386/

相关文章:

json - 使用 XPages 从托管 bean 获取数据

java - 我正在使用 ManyToOne , OneToMany 并且在获取数据时有无限循环

java - 从 android 到 mysql 进行查询是否安全?

flutter - 单击通知路由到特定的 flutter 屏幕

firebase - Flutter 从流中获取正确的值

c# - PowerShell 二进制模块程序集依赖性错误

jquery - 订阅 onChange jQuery dart

Dart:一次创建多个对象

Dart:如何从类中获取 "Type"

arrays - 无法接收要建模的数组