【问题标题】:get array of Timestamp from Firestore in Flutter从 Flutter 中的 Firestore 获取时间戳数组
【发布时间】:2021-04-15 05:05:26
【问题描述】:

我想从 Firestore 中获取一组 Timestamp 并将其存储在 Flutter 中的 DateTime 列表中, 我该怎么做?

我的 Firestore 数据:

我想获取这些值并在 Flutter 中将它们打印为 DateTime 类型

我的代码:

return StreamBuilder(
      stream: FirebaseFirestore.instance
          .collection('medicine')
    return StreamBuilder(
    stream: FirebaseFirestore.instance
    .collection('medicine')
    .where('userId', isEqualTo: watcherId)
    .snapshots(),
builder: (context, snapshot) {
if (snapshot.data == null) {
return Center(
child: CircularProgressIndicator(),
);
}
final doc = snapshot.data.docs;

return SizedBox(
height: 400.0,
child: ListView.builder(
itemCount: doc.length,
    itemBuilder: (ctx, index) {
    final docId = doc[index]['docId'];


//below I tried these but it didn't work
    // List dayOfMonth= List.from(doc[index]['selectedDates']);
    //Timestamp stamp = doc[index]['selectedDates'][index];
    //List<Timestamp> stamp = doc[index]['selectedDates'];
        return;
      }));
    
  });

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    首先从您的数据中获取日期:

    final dates = data[selectedDates]; // this should be a List<TimeStamp>
    
    

    然后转换它们:

    // ... make sure to check that dates is not null before mapping them
    final convertedDates = dates.map((date) => date.toDate()).toList();
    

    如果您希望将日期作为字符串,则只需使用date.toDate().toString()

    【讨论】:

      【解决方案2】:

      您可以使用 firestore TimeStamp 类将时间戳显示为日期

      Timestamp stamp = _data['selectedDates'][index];
      DateTime date = stamp.toDate();
      

      您可以通过以下方式格式化日期:

      DateFormat('dd-MM-yyyy').format(date); //returns a string
      

      【讨论】:

      • 出现这个错误('List'类型不是'Timestamp'类型的子类型)
      • 试试_data['selectedDates'][index]
      猜你喜欢
      • 2021-05-19
      • 2019-09-22
      • 2021-02-24
      • 1970-01-01
      • 2018-10-05
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多