I have 2 newbie questions here.
1st question: Why it won't go through the statement print('it will NOT go here.');
I got the error Null check operator used on a null value
. But I already added ?
to say that it can be null in the Price?
class.
2nd question: Why this statement if (_price != null)
shows The operand can't be null, so the condition is always true.
But I know that it can be null since it is possible that it is not existing. Please help me understand what's going on. Thanks!
This is my code:
DocumentReference<Map<String, dynamic>> docRefPrice =
db.collection('dataPath').doc('ThisIsNotExisting');
print('it will go here - 1');
final DocumentSnapshot<Map<String, dynamic>> documentSnapshotPrice = await docRefPrice.get();
print('it will go here - 2');
Price? _price = Price.fromFirestore(documentSnapshotPrice);
print('it will NOT go here.');
if (_price != null) {
print('_price is not null');
}
else { print('_price is null');
return false;
}
Edit add fromFirestore
:
factory Price.fromFirestore(DocumentSnapshot<Map<String, dynamic>> doc) {
Map data = doc.data()!;
return Price(
price1: data['text1'],
price2: data['text2'],
);
}
This is the link that I tried to understand: https://dart.dev/codelabs/dart-cheatsheet
CodePudding user response:
Regarding your first question, the function fromFirestore
is what's causing the error, add the code for it to your question.
the second question, _price
won't be null cause Price.fromFirestore(documentSnapshotPrice);
is a constructor so it will return a Price
object and never null.
Edit
Most probably this line is the reason for the error: Map data = doc.data()!;
remove the !
and make the Map
nullable and handle this case
I will need the Price
class code to write the code but here is the idea
factory Price.fromFirestore(DocumentSnapshot<Map<String, dynamic>> doc) {
Map? data = doc.data();
return Price(
price1: data == null ? null : data['text1'], // price1 must accept null in this case
price2: data == null ? null : data['text2'], // price2 must accept null in this case
);
}