Home > Back-end >  How to use a specific path to write/read data to firestore in flutter
How to use a specific path to write/read data to firestore in flutter

Time:07-14

I wanted to use dynamic paths selected by the user in my app to access/write data to my db. Sort of like a file path that the user can type, Eg: "users/mike/age". Using this string, I need to fetch as well as write data to the path in the db. Is there any way this is possible??

CodePudding user response:

Firebase works in a way like

Collections/Documents/Collections/Documents ...

You can create a Document & Collection dynamically in firebase, But you can not fetch any collection if are not known the name of Collection.

It means if there is a List of Documents in a Collection you can fetch the list by using its parent collection name but a List of Collection nested under a Document can not be fetched unless you are known to names.

For Example, if there is a path users/mike/age. You can fetch users because you know that you created a Collection named users and all of its Documents like mike can also be fetched. But if you have not known the age of user. You cannot fetch it.

CodePudding user response:

Kind of strange, but you could split the string then refactor with firebase path.

String pathStr = 'users/mike/age';
List<String> list = pathStr.split('/'); //now we have a list with the fields.
var ref;
switch (list.length) {
  case 0:
    break;
  case 1:
    ref = FirebaseFirestore.instance.collection(list[0]);
    break;
  case 2:
    ref = FirebaseFirestore.instance.collection(list[0]).doc(list[1]);
    break;  
  case 3:
    ref = FirebaseFirestore.instance.collection(list[0]).doc(list[1]).collection(list[2]);
    break;    
  case 4:
    ref = FirebaseFirestore.instance.collection(list[0]).doc(list[1]).collection(list[2]).doc(list[3]);
    break;      
  default: ref = null;
}
//Do whatevar with the ref path.
  • Related