I am new to Dart null safety but I hack more than 20 years in languages like C/C++, C#, Java and some more.
From my Flutter app I call REST APIs on a server that was written in C# and runs in a Docker container. The object returned by the REST API has a Dart DTO which was generated by a code generator. This generator declares all members as nullable. Here is a sample:
class BscGetCreditCardListResponse implements IConvertible
{
List<BscCreditCard>? creditCardList;
ResponseStatus? responseStatus;
BscGetCreditCardListResponse({this.creditCardList,this.responseStatus});
BscGetCreditCardListResponse.fromJson(Map<String, dynamic> json) { fromMap(json); }
fromMap(Map<String, dynamic> json) {
creditCardList = JsonConverters.fromJson(json['creditCardList'],'List<BscCreditCard>',context!);
responseStatus = JsonConverters.fromJson(json['responseStatus'],'ResponseStatus',context!);
return this;
}
Map<String, dynamic> toJson() => {
'creditCardList': JsonConverters.toJson(creditCardList,'List<BscCreditCard>',context!),
'responseStatus': JsonConverters.toJson(responseStatus,'ResponseStatus',context!)
};
getTypeName() => "BscGetCreditCardListResponse";
TypeContext? context = _ctx;
}
When I like to use the creditCardList
inside the response
object I have to write in Dart:
if (response != null &&
response.creditCardList != null &&
response.creditCardList!.length > 0) {
// do something here...
}
Why must I write in the last if condition response.creditCardList!.length > 0
?? If I write response.creditCardList.length > 0
(NO ! after creditCardList
) the compiler gives me an error saying creditCardList
could potentially be null. In my opinion this is NOT true since my second if condition is response.creditCardList != null
and therefore tests for null
. In C# for example it would NEVER reach response.creditCardList!.length > 0
if the result of response.creditCardList != null
is false
.
And if I follow this logic, why does the compiler accept response.creditCardList != null
and does not require response!.creditCardList != null
.
Could anybody please explain how this works?