I am trying to store my database value into a class, but i was unable to convert it into my class using DataSnapshot. I have already added all necessary null safety operators. But it still shows an error.
class User {
String userID = "";
String name = "";
String phoneNo = "";
String email = "";
String password = "";
User(
{required this.userID,
required this.name,
required this.phoneNo,
required this.email,
required this.password});
User.fromSnapshot(DataSnapshot dataSnapshot) {
userID = dataSnapshot.key!;
if (dataSnapshot.value != null) {
name = dataSnapshot.value!["name"] as String;
email = dataSnapshot.value!['email'];
phoneNo = dataSnapshot.value!['phone'];
password = dataSnapshot.value!['password'];
}
}
}
I am trying to define the snapshot value as a String but also the same as others.
CodePudding user response:
try
if (dataSnapshot.value != null) {
final data = dataSnapshot.value as Map;
name = data["name"] as String;
email = data['email'] as String;
phoneNo = data['phone'] as String;
password = data['password'] as String;
}
CodePudding user response:
Try to specify the type of your DataSnapshot:
User.fromSnapshot(DataSnapshot<Map<String,dynamic>> dataSnapshot) {
userID = dataSnapshot.key!;
if (dataSnapshot.value != null) {
name = dataSnapshot.value!["name"] as String;
email = dataSnapshot.value!['email'];
phoneNo = dataSnapshot.value!['phone'];
password = dataSnapshot.value!['password'];
}
}