Listen to changes and get info on updated fields only

Issue

I have Flutter/Firebase app, which allows users to store their book reading data into Firestore (books completed reading, reading currently etc). I would like to implement a feature, which allows users to see if someone completes reading a book (FS volume object field "completedUsers" updates) or someone starts reading a new book (FS account object field "nowReading" updates).

I think I should be using CollectionReference().snapshots().listen() – method for this, but I haven’t figured out how and how to set it up with StreamBuilder, so I could get exact info on which part of db object was updated.

Here are my models on user account and volume:

@JsonSerializable(explicitToJson: true)
class Account {
  String name;
  String uid;
  List<Volume> nowReading;
  List<Volume> wantToRead;
  List<Account> friends;
  Map<String, Volume> tips;

  Account(
      {this.name,
      this.uid,
      this.nowReading,
      this.wantToRead,
      this.friends,
      this.tips});

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

  Map<String, dynamic> toJson() => _$AccountToJson(this);
}
@JsonSerializable(explicitToJson: true)
class Volume {
  String id;
  String title;
  String description;

  String smallThumbnail;
  String bigThumbnail;

  List<String> authors;
  List<String> categories;

  int published;
  int pageCount;

  double averageGoogleRating;
  double averageUserRating;
  List<UserReview> userReviews;
  List<String> completedUsers;

  Volume(
      {this.id,
      this.title,
      this.description,
      this.smallThumbnail,
      this.bigThumbnail,
      this.authors,
      this.categories,
      this.published,
      this.pageCount,
      this.averageGoogleRating,
      this.averageUserRating,
      this.userReviews,
      this.completedUsers});

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

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

Solution

Firestore notifies clients when a document has changed, but not what specific fields within that document have changed. If you application needs that information, you will have to compare the previous DocumentSnapshot and the new version yourself in your application code.

Answered By – Frank van Puffelen

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *