简体   繁体   中英

How to get a time distance from firestore to flutter

I want to get a time distance from firestore and there are 93 documents so this function takes few minutes to go through all the documents

and this is my code for the calculation -

  int length;
  DateTime earlyTime;
  DateTime lateTime;
  String name;
  String finalName;

  QuerySnapshot snaps =
      await Firestore.instance.collection('nameDetails').getDocuments();
  List<DocumentSnapshot> snapCount = snaps.documents;
  length = snapCount.length;
  // Count of Documents in Collection

  for (int count = 1; count < length; count++) {
    print(count);
    await Firestore.instance
        .collection('nameDetails')
        .document(count.toString())
        .get()
        .then(
      (time) {
        //Parsing the strings into DateTime
        earlyTime = DateTime.parse(time['beforeTime']);
        lateTime = DateTime.parse(time['afterTime']);
        name = time['name'];
        print(name);
      },
    );
    if (birthDayTime.isAfter(earlyTime) && birthDayTime.isBefore(lateTime)) {
      name = finalName;
      break;
    }
  }
} 

So are there any efficient way to do this? if someone can help me it would be great:)

You are retrieving the documents inside the collection nameDetails twice which is not really needed. If you just want to retrieve the distance, you can just do the following:

          QuerySnapshot snaps =
              await Firestore.instance.collection('nameDetails').getDocuments();
          for (var docs in snaps.documents) {
            earlyTime = DateTime.parse(docs['beforeTime']);
            lateTime = DateTime.parse(docs['afterTime']);
            name = docs['name'];
            print(name);
            if (birthDayTime.isAfter(earlyTime) &&
                birthDayTime.isBefore(lateTime)) {
              name = finalName;
              break;
            }
          }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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