37

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?

1
  • Edit your Question with updated code & new Error Commented Dec 7, 2018 at 10:50

5 Answers 5

48

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 :

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for you help, I tried it, But now I am getting error:
The error states: The argument type 'Map<String, dynamic>' can't be assigned to the parameter type 'List'
You need to add more Code for me to debug. Plus the new error could be of some other area of code also.
FieldValue.arrayUnion takes in a list. Use this and it should fix your error - Firestore.instance.collection(city).document('Attractions').updateData({"data": FieldValue.arrayUnion([obj])});
17

@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)});

4 Comments

where are you using 'list' objects while updating your data in firestore?
He meant to use it instead of 'obj' in FieldValue.arrayUnion(obj). Easier way is just to do FieldValue.arrayUnion([obj]).
@AlexHartford I know, I just thought that it would be easier to understand and notice if I made it two statements instead of one
You still need to correct obj -> list with your current answer.
7

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'));
    

Comments

5

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"]),
});

Comments

2

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);
    }
  }

'''

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.