Home > database >  Use FieldValue.arrayUnion in Flutter with Cloud FireStore
Use FieldValue.arrayUnion in Flutter with Cloud FireStore

Time:09-09

fairly new to Flutter. I'm trying to update an Array field that contains a List Map of type <String, dynamic>. The data structure I'm trying to achieve looks similar to the image below: Data Structure

In order to update the "notes" field for my custom object without overwriting the entire Array, I'm using FieldValue.arrayUnion with SetOptions(merge: true)like so during a call to an update function :

 notes: FieldValue.arrayUnion([
                                      {
                                        "date": DateTime.now(),
                                        "notes": "some test notes",
                                        "user": "some user name",
                                      }
                                    ]),

The "notes" field is part of a much larger Object and is defined as being of type nullable List of type Map<String, dynamic> like so:

List<Map<String, dynamic>>? notes;

The problem is surfacing with this error:

The argument type 'FieldValue' can't be assigned to the parameter type 'List<Map<String, dynamic>>?'.

and in looking at every example I've come across it looks like the function "FieldValue.arrayUnion" will only accept a String value for the field name to update. Below is a code sample from the FireStore documentation at this link: enter image description here

CodePudding user response:

Your toFirestore is expecting notes to be of type List<Map<String, dynamic>>?, not FieldValue.arrayUnion (and that is okay). Update your data like this:

try {
  final schedulerEventJson = SchedulerEvent(
    title:
        '${_firstNameFormFieldController.text} ${_lastNameFormFieldController.text}',
    fname: _firstNameFormFieldController.text,
    lname: _lastNameFormFieldController.text,
    from: targetEvent.from,
    to: targetEvent.to,
    // remove notes from here.
    background: null,
    isAllDay: false,
  ).toFireStore();

  // here I set the value of notes directly into the json
  schedulerEventJson['notes'] = FieldValue.arrayUnion([
    {
      "date": DateTime.now(),
      "notes": "some new notes4",
      "user": "some different user4",
    },
  ]);
  await FirebaseFirestore.instance
      .collection('SchedulerEventCollection')
      .doc(targetEvent.key)
      .set(schedulerEventJson, SetOptions(merge: true));
  formSubmit("Updated the Event!");
} on Exception catch (e) {
  formSubmit("Error submitting your event! ${e.toString()}");
}
  • Related