【问题标题】:Flutter dart Error with converting timestamp to date without time颤振飞镖错误将时间戳转换为没有时间的日期
【发布时间】:2023-07-13 08:57:01
【问题描述】:

我将膳食和日期存储在 Cloud_Firestore 中,没有时间。取回它会增加时间。 现在我想删除时间,只剩下日期。

我尝试了下面显示的以下代码,但出现错误。从 dart 和 cloud_firestore 文档中,我找不到将其更改为时间的公共方法。 formatter.format(now) 错误调用:

I tried this Solution

aswell as this

String now The argument type 'String' can't be assigned to the parameter type 'DateTime'.

════════ Exception caught by widgets library ═══════════════════════════════════
Class 'Timestamp' has no instance method 'now'.
Receiver: Instance of 'Timestamp'
Tried calling: now()
The relevant error-causing widget was
    StreamBuilder<QuerySnapshot>

代码

import 'package:flutter/material.dart';
import 'package:mealapp/models/Widgets/whenAndWhatToEat.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:intl/intl.dart';
import 'package:mealapp/models/global.dart';

class MealTile extends StatefulWidget {
  final MealsAndWhen mealsAndWhen;
  MealTile ({ this.mealsAndWhen });

  @override
  MealTileState createState() {
    return MealTileState();
  }
}
class MealTileState extends State<MealTile> {
  String id;
  final db = Firestore.instance;
  String meal;


  Widget buildItem(DocumentSnapshot doc) {
   var now = '${doc.data['Date'].toDate()}';
   var formatter = new DateFormat('dd-MM-yyyy');
    String formatted = formatter.format(now);
    print (formatted);
    return Container(
        margin: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text(
              'Meal: ${doc.data['Meal']}',
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Colors.white),
              textAlign: TextAlign.center,
            ),
            Text(
              'Date: ${doc.data['Date']}',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                SizedBox(width: 8),
                FlatButton(
                  onPressed: () => deleteData(doc),
                  child: Text('Delete',
                  style: TextStyle(fontWeight: FontWeight.bold,
                  color: Colors.white)
                  ),
                ),
              ],
            ),
          ],
        ),
        decoration: BoxDecoration(
          color: lightBlueColor,
          borderRadius: BorderRadius.all(Radius.circular(12)),
        ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: darkGreyColor,
      body: ListView(
        padding: EdgeInsets.only(top: 220),
        children: <Widget>[
          StreamBuilder<QuerySnapshot>(
            stream: db.collection('mealList').snapshots(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Column(children: snapshot.data.documents.map((doc) => buildItem(doc)).toList());
              } else {
                return SizedBox();
              }
            },
          )
        ],
      ),
    );
  }

  void deleteData(DocumentSnapshot doc) async {
    await db.collection('mealList').document(doc.documentID).delete();
    setState(() => id = null);
  }
}

【问题讨论】:

    标签: datetime flutter dart google-cloud-firestore intl


    【解决方案1】:

    当您在引号中使用 DateTime 时将其转换为字符串,并且不会在编译时出错,因为您将其分配给 var 而不是 DateTime。在大多数情况下,避免使用var 并明确变量的类型;

    DateTime now = doc.data['Date'].toDate();
    DateFormat formatter = DateFormat('dd-MM-yyyy');
    String formatted = formatter.format(now);
    

    【讨论】: