1
votes

How do you create a sub-collection in Firestore with Flutter based on a dynamic uid?

Architecture should look like this: users (collection) --> UID (document - unique to each user) --> vault (collection) --> credential (document)

I am currently using the implementation below, which obviously when called just creates the architecture I need except for using a string "uid" in place of the dynamic uid of the user as the document that the vault collection resides in. How to change this so that the document('uid') element is the actual uid document of the current user rather than just the string "uid"?

import 'package:mindpass/models/user.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class DatabaseService {

  final String uid;
  DatabaseService({ this.uid });
  String credential;

  // collection reference
  final CollectionReference vaultCollection = Firestore.instance.collection('users').document('uid').collection('vault');

  Future<void> updateVaultData(String credUN, String timeStamp) async {
    return await vaultCollection.document(credential).setData({
    'credUN': '"aribtraryUN"',
    'timeStamp': Timestamp.now()
  });
  }
1

1 Answers

3
votes

If the user is signed in with Firebase Authentication, you can get their UID with:

var user = await FirebaseAuth.instance.currentUser();
var uid = user.uid;

And then get their vault collection with:

final CollectionReference vaultCollection = Firestore.instance.collection('users').document(uid).collection('vault');