Home > Blockchain >  Flutter Firestore create new Array every time function called
Flutter Firestore create new Array every time function called

Time:02-17

As per the question I'd like to add a new array every time I call my addPredection function for example I'd like it to look like this.

Currently its just updating the current value everytime

enter image description here

My code is as follows:

///add prediction function
  Future<String?> addPrediction() async {
    var currentUser = FirebaseAuth.instance.currentUser;
    var todaysDate = DateTime.now().toString();


    var doesExist = await FirebaseFirestore.instance
        .collection('collection')
        .doc(currentUser!.uid)
        .get();
    if (doesExist.exists == true) {
      FirebaseFirestore.instance
          .collection('userMoods')
          .doc(currentUser!.uid)
          .update({
        'Predictions':
        FieldValue.arrayUnion([todaysDate,'angry', 'Happy'])
      });
    }
    if (doesExist.exists == false) {
      FirebaseFirestore.instance
          .collection('userMoods')
          .doc(currentUser!.uid)
          .set({
        todaysDate: FieldValue.arrayUnion(['angry', 'Happy'])
      }, SetOptions(merge: false));
    }

CodePudding user response:

For adding items you also have to apply the SetOptions but with the merge set to true, like this:

var todaysDate = DateTime.now().toString();

FirebaseFirestore.instance
    .collection('userMoods')
    .doc(currentUser!.UID).set({
      todaysDate : ['angry', 'happy']
    }, SetOptions(merge: true));

I did it on my end and I believe they come out the way you want:

enter image description here

The merge: true on the SetOptions what it does is that it appends to the existing document. The set method by default overrides the existing fields unless the merge: true option is there.

  • Related