Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Firebase firestore append data with unique ID

I'm working on the Flutter app where users can save multiple addresses. Previously I used a real-time database and it was easier for me to push data in any child with a unique Id but for some reason, I changed to Firestore and the same thing want to achieve with firestore. So, I generated UUID to create unique ID to append to user_address

This is how I want

enter image description here

and user_address looks like this

enter image description here

And this is how it's getting saved in firestore

enter image description here

So my question Is how I append data with unique id do I have to create a collection inside users field or the above is possible?

Below is my code I tried to set and update even user FieldValue.arrayUnion(userServiceAddress) but not getting the desired result

var uuid = Uuid();
var fireStoreUserRef =
    await FirebaseFirestore.instance.collection('users').doc(id);

Map locationMap = {
  'latitude': myPosition.latitude,
  'longitude': myPosition.longitude,
};

var userServiceAddress = <String, dynamic>{
  uuid.v4(): {
    'complete_address': completedAddressController.text,
    'floor_option': floorController.text,
    'how_to_reach': howtoreachController.text,
    'location_type': locationTag,
    'saved_date': DateTime.now().toString(),
    'user_geo_location': locationMap,
    'placeId': addressId
  }
};

await fireStoreUserRef.update({'user_address':  userServiceAddress});

If I use set and update then whole data is replaced with new value it's not appending, so creating a collection is the only solution here and If I create a collection then is there any issue I'll face?

like image 705
Niraj Avatar asked Jul 11 '26 22:07

Niraj


1 Answers

You won't have any issues per se by storing addresses in a separate collection with a one-to-many relationship, but depending on your usage, you may see much higher read/write requests with this approach. This can make exceeding your budget far more likely.

Fortunately, Firestore allows updating fields in nested objects via dot notation. Try this:

var userServiceAddress = {
  'complete_address': completedAddressController.text,
  'floor_option': floorController.text,
  'how_to_reach': howtoreachController.text,
  'location_type': locationTag,
  'saved_date': DateTime.now().toString(),
  'user_geo_location': locationMap,
  'placeId': addressId
};

await fireStoreUserRef.update({'user_address.${uuid.v4()}':  userServiceAddress});
like image 136
Lee3 Avatar answered Jul 14 '26 13:07

Lee3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!