flutter - 颤振 if-else 语句
问题描述
{"data":[{"id":"32f","regionName":"Korea","companyName":"Machine","catDealerCode":null},{"id":"cbb","regionName" :"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;
} }
解决方案
我会使用可识别空值的运算符:
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}');
}
});
},
推荐阅读
- opentok - OpenTok 发布者音量调整
- sql - 如果数据库不存在则创建数据库
- c++ - 使用 vcpkg 重建 boost-thread 包,无需重新下载
- javascript - 如何使用正则表达式从文本中提取数字
- yii2 - 无法通过 Composer 升级 Yii2 版本
- spring-boot - Spring Boot Java 请求 GET 请求映射 URL 问题
- docker - Flask 和 React Docker 容器不通过 Docker-Compose 进行通信
- java - 无法访问暴露端口上的 docker 容器化 Java Web 应用程序
- android - 如果我单击 Recycler 视图,那么如何进行新活动?
- javascript - jQuery 表格分页和引导按钮在 IE10 和 11 中不起作用