firedart icon indicating copy to clipboard operation
firedart copied to clipboard

arrayUnion (Add field in array)

Open haleem13 opened this issue 2 years ago • 1 comments

Can anyone please help me to Add field in array???? Firestore.instance .collection('YourCollection') .document('YourDocument') .updateData({'array':FieldValue.arrayUnion(['data1','data2','data3'])});

haleem13 avatar Mar 25 '22 10:03 haleem13

Here's an extension method that you can use for this purpose created by me and some LLM model

import 'package:firedart/firedart.dart';

extension DocumentReferenceExtension on DocumentReference {
  Future<void> updateArrayField(String fieldName, dynamic item) async {
    if (!(await this.exists)) {
      await this.set({fieldName: [item]});
    } else {
      final doc = await this.get();
      final currentItems = doc[fieldName] as List<dynamic>? ?? [];
      await this.update({fieldName: [...currentItems, item]});
    }
  }
}

usage

    final docRef = collection.document(docId);
    await docRef.updateArrayField('items', json);

mostly by some LLM model...

Defuera avatar Nov 10 '23 22:11 Defuera