Almog
Almog

Reputation: 2837

Flutter Firestore Stream to json model error

I'm trying to parse my Google Firestore stream query with my model using the from JSON method I'm getting an error 'argument_type_not_assignable' which I understand but not really sure what is the correct way to do this

Here is my steam code

// Gets user as a stream
  Stream<UserModel> getUserStream() {
    final userId = _auth.currentUser?.uid;
    return usersCollection
        .doc(userId)
        .snapshots(
          includeMetadataChanges: true,
        )
        .map(
          (DocumentSnapshot<Map<String, dynamic>> snapshot) =>
              UserModel.fromJson(snapshot.data()!),
        );
  }

The error I'm getting

The argument type 'UserModel Function(DocumentSnapshot<Map<String, dynamic>>)' can't be assigned to the parameter type 'UserModel Function(DocumentSnapshot<Object?

Here is the user model

class UserModel {
  String userId;
  String email;
  String firstName;
  String lastName;
  @JsonKey(fromJson: dateTimeFromTimestamp, toJson: dateTimeAsIs)
  DateTime? recentTraining;
  @DocumentSerializerNullable()
  DocumentReference? recentTrainingRef;
  int dogsCount;
  int totalTrainingSessions;
  int totalTrainingTime; // in min
  int totalTrainingDays;
  @JsonKey(fromJson: dateTimeFromTimestamp, toJson: dateTimeAsIs)
  DateTime? createdAt;
  AccountType accountType;
  UserType userType;
  Subscription subscription;
  String? organization;
  String? organizationWebsite;
  String? role;

  UserModel({
    required this.userId,
    required this.email,
    required this.firstName,
    required this.lastName,
    required this.createdAt,
    required this.dogsCount,
    required this.totalTrainingSessions,
    required this.totalTrainingTime,
    required this.totalTrainingDays,
    required this.accountType,
    required this.userType,
    required this.subscription,
    this.recentTraining,
    this.recentTrainingRef,
    this.organization,
    this.organizationWebsite,
    this.role,
  });

  factory UserModel.fromJson(Map<String, dynamic> json) =>
      _$UserModelFromJson(json);

  Map<String, dynamic> toJson() => _$UserModelToJson(this);
}

Upvotes: 1

Views: 593

Answers (1)

Almog
Almog

Reputation: 2837

I was able to fix using with converter

Stream<DocumentSnapshot<UserModel>> getUserStream() {
    final userId = _auth.currentUser?.uid;
    return usersCollection
        .doc(userId)
        .withConverter<UserModel>(
          fromFirestore: (snapshot, _) => UserModel.fromJson(snapshot.data()!),
          toFirestore: (user, _) => user.toJson(),
        )
        .snapshots(
          includeMetadataChanges: true,
        );

Upvotes: 2

Related Questions