简体   繁体   English

如何从 Flutter 中的 Firestore 获取值

[英]How to get values from Firestore in Flutter

I need to get the values inside my Firestore document which has a sub collection.我需要获取具有子集合的 Firestore 文档中的值。

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:另外,我尝试完成的是在userPolls集合上,我需要根据userId添加一个带有Id的文档,然后创建一个 'dailyPolls' 的集合,该集合具有一个Id为当前日期但没有 ' /' 并在其中放置我所有的数据,如下所示:

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.在检索数据时,我需要访问userPolls ,然后获取具有Id的文档,即userId ,然后转到dailyPolls的集合,然后获取具有基于当前日期的Id的文档,而没有 '/ ' 然后获取其中的数据。

 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);
    });
  }

在此处输入图片说明

The red square is the path and the blue is what I need红色方块是路径,蓝色方块是我需要的

I am very new to flat databases.我对平面数据库很陌生。

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.如果仍然有问题,请检查第一个print语句的输出以查看其值是否与您在数据库中看到的值匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM