首页 > 解决方案 > 如何按特定顺序从 firebase 检索数据?

问题描述

数据库结构图

在我的 Flutter 应用程序中,我希望排序的数据取决于特定用户的药物列表中存在的最后日期,那么我该如何编写 Firebase 查询呢?我正在使用 Firebase Firestore。

标签: databasefirebasefluttergoogle-cloud-firestore

解决方案


Try something like this (code has not yet been tested):

List<dynamic> getMedicinesSorted() async {
  final snapshot = await FirebaseFirestore.instance
    .collection('users/tnzdrlpLD1hfJJ6o8iMV/MedicinesList')
    .get();

  final sorted = snapshot.docs.sort((docA, docB) => 
    new DateTime.fromMicrosecondsSinceEpoch(docA.data()['Last_Date']).compareTo(
      new DateTime.fromMicrosecondsSinceEpoch(docB.data()['Last_Date'])
    )
  );

  return sorted;
}

推荐阅读