How to get values from Firestore in Flutter

Viewed 540

I need to get the values inside my Firestore document which has a sub collection.

ADD DATA TO DB

In adding, what I try to accomplish is on the userPolls collection, I need to add a document with an Id based on the userId then create a collection of 'dailyPolls' that has a document with an Id of the current date but without the '/' and in it is where I put all my data like so:

final CollectionReference userPollCollection =
      Firestore.instance.collection('userPolls');
Future setPoll(UserPoll userPoll) async {
    var dt = userPoll.pollDate.replaceAll('/', '');
    return await userPollCollection
        .document(userId)
        .collection('daillyPolls')
        .document(dt)
        .setData({
      'uid': userId,
      'pollDate': userPoll.pollDate,
      'status': userPoll.status,
      'statusCode': userPoll.statusCode
    });
  }

QUERYING DATA FROM DB

In retrieving data, I need to get to the userPolls, then get the document with an Id which is the userId, then go to the collection of dailyPolls, then get the document with an Id which is based on the current date without the '/' then get the data which is inside it.

 Future getPoll() async {
    final DateTime now = DateTime.now();
    final DateFormat formatter = DateFormat('yyyy/MM/dd');
    final String formatted = formatter.format(now);
    var pollDate = formatted;
    var dt = pollDate.replaceAll('/', '');

    var docRef = userPollCollection
        .document(userId)
        .collection('dailyPolls')
        .document(dt);

    docRef.get().then((onValue) {
      print(onValue.data);
    });
  }

enter image description here

The red square is the path and the blue is what I need

I am very new to flat databases.

1 Answers

I'm not sure what the classes are you are trying to use, but here is the simplest way I can get a date in the right format:

final DateTime now = DateTime.now();
final DateFormat formatter = DateFormat('yyyy/MM/dd');
final String formatted = formatter.format(now);

print(formatted);

var docRef = userPollCollection
    .document(userId)
    .collection('dailyPolls')
    .document(formatted);

To then get the status field, you'd do:

docRef.get().then((onValue) {
  print(onValue.data().status);
});

If you're still having problem, check the output of the first print statement to see if its value matches what you see in the database.

Related