0

I Store the Meal and the Date in Cloud_Firestore without the Time. Getting it back it adds Time. Now i want to remove the Time so that only the Date is left.

I tried the following Code shown below there i get the Error. From the dart and cloud_firestore Documentiation i can't find Public Method for changing it to Time. The formatter.format(now) Error called:

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>

Code

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

Screenshot of App

Tempelritter
  • 471
  • 9
  • 22

1 Answers1

1

You convert the DateTime to the string when you use it inside quotes and don't get error in compile time because you assign it to var instead of DateTime. In most of cases avoid to use var and make clear type of your variables;

DateTime now = doc.data['Date'].toDate();
DateFormat formatter = DateFormat('dd-MM-yyyy');
String formatted = formatter.format(now);
Mehmet Ali Bayram
  • 7,222
  • 2
  • 22
  • 27