Sami Ullah
Sami Ullah

Reputation: 439

flutter firestore, add new object in array

I have array of objects, I want to add new object when user enter new data in the array?

Firestore.instance.collection(city).document('Attractions').updateData(
                        "data", FieldValue.arrayUnion(obj)
                      );

This shows error, How can I achieve this with flutter?

Upvotes: 37

Views: 39314

Answers (5)

Mans
Mans

Reputation: 3261

2023 Updated Syntax:

From the Fireabse docs

final washingtonRef = db.collection("cities").doc("DC");

// Atomically add a new region to the "regions" array field.
washingtonRef.update({
  "regions": FieldValue.arrayUnion(["greater_virginia"]),
});

// Atomically remove a region from the "regions" array field.
washingtonRef.update({
  "regions": FieldValue.arrayRemove(["east_coast"]),
});

Upvotes: 5

CopsOnRoad
CopsOnRoad

Reputation: 267404

Null safe code:

Say this is the data you want to add

Map<String, dynamic> someData = {
  'foo': 1,
  'bar': true,
};
  • Add the data with unique auto-generated ID:

    var collection = FirebaseFirestore.instance.collection('collection');
    collection 
        .add(someData) 
        .then((_) => print('Added'))
        .catchError((error) => print('Add failed: $error'));
    
  • Add the data with your own ID:

    var collection = FirebaseFirestore.instance.collection('collection');
    collection 
        .doc('document_id') // <-- Document ID
        .set(someData) 
        .then((_) => print('Added'))
        .catchError((error) => print('Add failed: $error'));
    
  • Add the object to an array:

    var collection = FirebaseFirestore.instance.collection('collection');
    collection 
        .doc('document_id') // <-- Document ID
        .set({'data': FieldValue.arrayUnion(list)}) // <-- Add data
        .then((_) => print('Added'))
        .catchError((error) => print('Add failed: $error'));
    

Upvotes: 7

Gabe
Gabe

Reputation: 6865

@anmol.majhail 's is right, but to solve @Sami Ullah's problem, you must first make a list and add the object into the list like this:

var list = [objectBeingAdded];
Firestore.instance.collection('city').document('Attractions').updateData({"data": FieldValue.arrayUnion(list)});

Upvotes: 17

Lyman Perrine
Lyman Perrine

Reputation: 21

This is a working function I built that adds new Maps to an array in my Firestore Services class. I'm using Json Serializable to annotate all my model classes. userTemplateSections is a data field in my userTemplate firestore documents. I take userTemplate as a constructor of the 'addUserTemplateSection' function to make sure I'm editing the correct document.

I also added the function I made to delete Maps from a firestore document array.

'''

Future<void> addUserTemplateSection(
      {UserTemplate userTemplate, String title, String summary}) async {
    try {
      final UserTemplateSection userTemplateSection =
          UserTemplateSection(title: title, summary: summary);
      await _firestore
          .document(FirestorePath.userTemplate(uid, userTemplate.id))
          .updateData(
        {
          'userTemplateSections':
              FieldValue.arrayUnion([userTemplateSection.toJson()])
        },
      );
    } catch (e) {
      print(e);
    }
  }

'''

'''

Future<void> deleteUserTemplateSection({
    UserTemplate userTemplate,
    UserTemplateSection userTemplateSection,
  }) async {
    try {
      await _firestore
          .document(FirestorePath.userTemplate(uid, userTemplate.id))
          .updateData(
        {
          'userTemplateSections':
              FieldValue.arrayRemove([userTemplateSection.toJson()])
        },
      );
    } catch (e) {
      print(e);
    }
  }

'''

Upvotes: 2

anmol.majhail
anmol.majhail

Reputation: 51176

Right Format is :

Firestore.instance.collection(city).document('Attractions').updateData({"data": FieldValue.arrayUnion(obj)});

updateData Take Map<String,dynamic> as data.

In your Code you are having , as separator between key - value instead it should be :

Upvotes: 48

Related Questions