I am little confused while writing a simple class as below:
class NewsSource {
final String url;
final String name;
final String imageUrl;
NewsSource({required this.url, required this.name, required this.imageUrl});
factory NewsSource.fromFireStore(
DocumentSnapshot<Map<String, dynamic>> snapshot,
SnapshotOptions? options) {
final data = snapshot.data();
return NewsSource(
url: data?['url'], name: data?['name'], imageUrl: data?['imageUrl']);
}
Map<String, dynamic> toFireStore() {
return {"url": url, "name": name, "imageUrl": imageUrl};
}
}
fromFireStore function call NewsSource constructor where parameters can be null clearly but still dart is not complaining why?
PS: If I remove dynamic then it starts to complain, I guess any use of dynamic makes null check redundant.
CodePudding user response:
This: Map<String, dynamic> toFireStore()
is mapping every type to a dynamic
, which is not null-safe.
Dynamic allows non-nullable or nullable types assigned.
CodePudding user response:
It's because of dynamic
. Variables of type dynamic
are basically not null-safe and still need to be handled accordingly.
My guess is that if we assume the map is not null then data?['url']
would return a variable of type dynamic
for which null
is also a valid value. And variables of type dynamic
are never checked for null-safety. So it doesn't even bother to complain whether the map is null