flutter: 用于空值的空检查运算符
flutter: 用于空值的空检查运算符
我有一个商业模型。我在post api中使用了该模型来发布数据。
但是当我将数据存储在这个 Business? business = Business(); business.bank!.bankName = _selectedIdProof.toString();
中时,我遇到了错误。
请帮帮我,我不知道如何解决这个问题。
以下是我的商业模型:
import 'package:evillage_app/models/business/bank/bank.dart';
import 'package:evillage_app/models/business/hours/hours.dart';
import 'package:evillage_app/models/business/proof/proof.dart';
import 'package:evillage_app/models/utils/attachment/attachment.dart';
import 'package:evillage_app/models/utils/map/map.dart';
import 'package:json_annotation/json_annotation.dart';
part 'business.g.dart';
@JsonSerializable()
class Business {
String? id;
String? name;
String? contact;
String? website;
String? address;
String? landmark;
String? area;
String? pincode;
String? country;
String? state;
String? district;
String? tehsil;
String? villagePanchayat;
MapModel? map;
String? category;
String? aboutShop;
String? minimumPurchase;
Proof? idProof;
Proof? panProof;
Proof? addressProof;
Proof? gst;
Proof? registrationCertificate;
Bank? bank;
List
List
List
Attachment? logoMedia;
bool? status;
factory Business.fromJson(Map
Business({
this.id,
this.name,
this.contact,
this.website,
this.address,
this.landmark,
this.area,
this.pincode,
this.country,
this.state,
this.district,
this.tehsil,
this.villagePanchayat,
this.map,
this.category,
this.aboutShop,
this.minimumPurchase,
this.idProof,
this.panProof,
this.addressProof,
this.gst,
this.registrationCertificate,
this.bank,
this.upi,
this.hours,
this.media,
this.logoMedia,
this.status,
});
Map
}
这是我的银行模型:
import 'package:json_annotation/json_annotation.dart';
part 'bank.g.dart';
@JsonSerializable()
class Bank {
String? bankName;
String? branchName;
String? type;
String? accountNumber;
String? ifscCode;
String? micrCode;
String? beneficiaryName;
factory Bank.fromJson(Map
Bank({
this.bankName,
this.branchName,
this.type,
this.accountNumber,
this.ifscCode,
this.micrCode,
this.beneficiaryName,
});
Map
}
在Flutter中出现(flutter: Null check operator used on a null value)这个问题是因为在对一个空值进行非空检查操作。Dart语言提供了null安全性特性来帮助我们找出这样的错误。当我们尝试在一个null值上进行操作时,Dart会提示这个问题的出现位置。
在你的情况下,问题出现在你的Business()
对象上,它的一个属性Bank? bank
被定义为可空(使用了?
操作符)。在你的submit()
方法中,你创建了一个空的Business()
对象,默认情况下构造函数会将bank
属性填充为null。当你在这里尝试访问它时:
business.bank!.bankName = _selectedIdProof.toString();
你强制Dart在bank
上调用bankName
属性,但是bank
是null,所以Dart会抛出异常。
你可以通过提高代码质量来避免使用null值,除非对于你的业务逻辑来说是有意义的;或者避免使用非空检查操作符!
,除非你百分之百确定该值不会为null。而是更倾向于使用null安全操作符?
,例如?.
、??
、??=
等。
因此,解决这个问题的方法有两种:一是提高代码质量,避免使用null值;二是避免使用非空检查操作符!
,而是使用null安全操作符?
。