I have been working on flutter for few months now, and I got to understand how to fix null safety issues but this one is really complicated for me and i would like to get helped.
Here is my problem:
Whenever I am trying to sign in, I am getting this error: 'Null' type is not a subtype of type Map<string, dynamic> I tried my best to figure out what goes wrong but I am unable, any help will be a life saving...
import 'package:cloud_firestore/cloud_firestore.dart';
class User {
final String email;
final String uid;
final String photoUrl;
final String username;
final String bio;
final List followers;
final List following;
const User({
required this.email,
required this.uid,
required this.photoUrl,
required this.username,
required this.bio,
required this.followers,
required this.following,
});
then i continued here
Map<String, dynamic> toJson() => {
"username": username,
"uid": uid,
"email": email,
"photoUrl": photoUrl,
"bio": bio,
"followers": followers,
"following": following,
};
static User fromSnap(DocumentSnapshot snap) {
var snapshot = snap.data() as Map<String, dynamic>;
return User(
username: snapshot['username'],
uid: snapshot['uid'],
email: snapshot['email'],
photoUrl: snapshot['photoUrl'],
bio: snapshot['bio'],
followers: snapshot['followers'],
following: snapshot['following'],
);
}
}
now I am getting the error on this line: null type is not a subtype of Map<string, dynamic>
var snapshot = snap.data() as Map<String, dynamic>;
this is all my problem, thanks in advance.
CodePudding user response:
Your snapshot
value is nullable
and you try to cast it to map
, instead of this:
var snapshot = snap.data() as Map<String, dynamic>;
try this:
var snapshot = snap.data() != null ? snap.data() as Map<String, dynamic> : {};
Also change your return to this:
return User(
username: snapshot['username']??””,
uid: snapshot['uid'] ??””,
email: snapshot['email'] ??””,
photoUrl: snapshot['photoUrl'] ??””,
bio: snapshot['bio'] ??””,
followers: snapshot['followers'] ??[],
following: snapshot['following'] ??[],
);