Home > front end >  FlutterFire update Array instead of replacing it
FlutterFire update Array instead of replacing it

Time:10-12

FireStore structure

so the menus field stores maps inside of an array/List. But when i want to add a map to menus it replaces all the existing ones with the new one, instead of adding a new one, here my code:

    Menu menuObj = Menu(
      name: menuName, categories: [
      Categories(
        name: categoryName,
      ),
    ]);

FirebaseFirestore.instance.doc('menus/${FirebaseAuth.instance.currentUser!.uid}')
        .set({
      'menus': [
        menuObj.toJson(),
      ]
    }, SetOptions(merge: true));

CodePudding user response:

I had to use this code instead:

    FirebaseFirestore.instance
        .doc('menus/${FirebaseAuth.instance.currentUser!.uid}')
        .set({
      'menus': FieldValue.arrayUnion([menuObj.toJson()])
    }, SetOptions(merge: true));

Important part is this: FieldValue.arrayUnion([menuObj.toJson()]).

  • Related