首页 > 解决方案 > 颤振 if-else 语句

问题描述

{"data":[{"id":"32f","re​​gionName":"Korea","companyName":"Machine","catDealerCode":null},{"id":"cbb","re​​gionName" :"Korea","companyName":"KR","catDealerCode":null},{"id":"b6125b0e-5ec9",,"regionName":"China","companyName":"CHN","catDealerCode ":null}],"code":0,"message":null}

我有你在上面看到的数据。我根据公司名称提取数据。但有些国家没有数据。我想在 this 中创建一个 if else 案例。但无论我说 element == null 时我做什么,它都不接受。有谁知道我在哪里做错了?我应该如何为空数据创建 if else ?

  onTap: () async {
        List<Country> country =
            await fetchList(
              snapshot.data.code);
    
   country.forEach((element) {
         if(element.companyName == null){
       print('element is empty');
     }else{
          print('Here ${element.companyName}');
                                        }
         });
            },

这是我的国家名单数据;

{"data":[{{"code":"KR","name":"Korea","isActive":true,"id":"71"},{"code":"RU","name ":"俄罗斯","isActive":true,"id":"3c"},{"code":"Ch","name":"China","isActive":true,"id":"86 "}],"code":0,"message":null}

 class Country {
  String id;
  String companyCode;
  String countryCode;
  String countryId;
  String regionName;
  String companyName;
  Null catDealerCode;

  Country(
      {this.id,
        this.companyCode,
        this.countryCode,
        this.countryId,
        this.regionName,
        this.companyName,
        this.catDealerCode});

  Couuntry.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    companyCode = json['companyCode'];
    countryCode = json['countryCode'];
    countryId = json['countryId'];
    regionName = json['regionName'];
    companyName = json['companyName'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['companyCode'] = this.companyCode;
    data['countryCode'] = this.countryCode;
    data['countryId'] = this.countryId;
    data['regionName'] = this.regionName;
    data['companyName'] = this.companyName;
    return data;
 

} }

标签: flutterif-statement

解决方案


我会使用可识别空值的运算符:

onTap: () async {
                              List<Country> country =
                                        await fetchList(
                                            snapshot.data.code);
    
                                      country?.forEach((element) {
                                        if(element?.companyName == null){
                                          print('element is empty');
                                        }else{
                                          print('Here ${element.companyName}');
                                        }
                                      });
                          },

推荐阅读