DEV Community

Curtly Critchlow
Curtly Critchlow

Posted on

How to Update Cloud Firestore Documents - #100DaysOfCode - Day 18

Introduction

This post is part of my 100DaysOfCode series. In this series, I write about what I am learning on this challenge. For this challenge, I will be learning flutter and firebase by building an Agriculture Management Information System.

Recap

On Day 17 we discussed how to reuse a use form widgets to handle create and update scenarios.

Overview

In this post, we'll discuss how to update our farmer documents in cloud firestore. We have already implemented the Add functionality so we will focus on the update functionality.

Update farmer command

class UpdateFarmerCommand extends BaseCommand {
  UpdateFarmerCommand(BuildContext c) : super(c);

  /// Calls FarmerService.updateFarmer method
  ///
  /// Recieves farmer data and buildcontext from widget and pass it to the farmerService.updateFarmer and fileService.uploadFarmerProfilePicture method.
  Future<bool> run({
    required FarmerServiceModel farmerServiceModel,
    required File? farmerProfilePicture,
    required BuildContext context,
  }) async {
    bool farmerAddedSuccess = false;

    if (farmerProfilePicture != null) {
      final farmerProfilePictureUrl =
          await fileservice.uploadFarmerProfilePicture(farmerProfilePicture);
      farmerServiceModel.saveProfilePicture(farmerProfilePictureUrl);
    }
    await farmerService
        .updateFarmer(farmerServiceModel: farmerServiceModel)
        .then((value) => farmerAddedSuccess = true);
    return farmerAddedSuccess;
  }
}
Enter fullscreen mode Exit fullscreen mode

This method accepts a FarmerServiceModel farmerServiceModel instance, an optional File? farmerProfilePicture and a BuildContext context. If the farmerProfilePicture is not null upload it to cloud storage and save the url. Call the farmerService.updateFarmer method.

Farmer Service updateFarmer method.

class FarmerService {
  final farmerRef =
      FirebaseFirestore.instance.collection('farmers').withConverter(
            fromFirestore: (snapshot, _) =>
                FarmerServiceModel.fromJson(snapshot.data()!),
            toFirestore: (farmerModel, _) => farmerModel.toJson(),
          );

  Future<void> updateFarmer({
    required FarmerServiceModel farmerServiceModel,
  }) async {
    return farmerRef
        .doc(farmerServiceModel.id)
        .update(farmerServiceModel.toJson())
        .then((value) => value)
        .catchError((error) {
      print(error.toString());
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

This method accepts a FarmerServiceModel farmerServiceModel instance. The .doc() and .update() method is called on farmerRef() where the farmerServiceModel.id and the farmerServiceModel.toJson() is passed the .doc() and .update() respectively.

The farmerServiceModel.toJson() method simply convert the farmerServiceModel properties to a Map.

Wrap Up

In this post, we discussed how to update a document in cloud firestore.

Connect with me

Thank you for reading my post. Feel free to subscribe below to join me on the #100DaysOfCodeChallenge or connect with me on LinkedIn and Twitter. You can also buy me a book to show your support.

Discussion (0)