firedart
firedart copied to clipboard
arrayUnion (Add field in array)
Can anyone please help me to Add field in array????
Firestore.instance .collection('YourCollection') .document('YourDocument') .updateData({'array':FieldValue.arrayUnion(['data1','data2','data3'])});
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...