I am not able to get rid of this error while returning userData
. It says-- "The argument type 'Object' can't be assigned to the parameter type 'Map<String, dynamic>'".
Future<User?> getUser({required String userId}) async {
log.i('userId:$userId');
if (userId.isNotEmpty) {
final userDoc = await usersCollection.doc(userId).get();
if (!userDoc.exists) {
log.v('We have no user with id $userId in our database');
return null;
}
final userData = userDoc.data();
log.v('User found. Data: $userData');
return User.fromJson(userData!); // This is where the error comes
} else {
throw FirestoreApiException(
message:
'Your userId passed in is empty. Please pass in a valid user if from your Firebase user.');
}
}
Below is my user model and I am using json_serializable: ^6.2.0
and freeze: ^2.0.3 1
in dev dependencies also freezed_annotation: ^2.0.3
and json_annotation: ^4.5.0
in dependencies in pubspec.yaml
file. I am not getting where it is going wrong. Someone, please help me resolve this.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'application_models.freezed.dart';
part 'application_models.g.dart';
@freezed
class User with _$User {
factory User({
required String id,
String? email,
}) = _User;
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
}
CodePudding user response:
Assuming you're using Firestore, you need to cast the object returned from userDoc.data()
to Map<String, dynamic>
:
final userData = userDoc.data() as Map<String, dynamic>;
Here's an example from the docs: https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document