0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Flutter】_TypeError (type 'Timestamp' is not a subtype of type 'DateTime')の解決法

Posted at

Firestoreから取得した段階ではTimeStamp

provider+Firebaseの構成で、Firestoreから値を取得するような以下のコードがあったとします。

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:lovedan/models/comment.dart';

class CommentProvider with ChangeNotifier {
  List<Comment>? comments;

  void fetchComments(String postId) async {
    final QuerySnapshot snapshot = await FirebaseFirestore.instance
        .collection('posts')
        .doc(postId)
        .collection('comments')
        .orderBy(
          'datePublished',
          descending: true,
        )
        .get();

    final List<Comment> _comments =
        snapshot.docs.map((DocumentSnapshot document) {
      Map<String, dynamic> data = document.data() as Map<String, dynamic>;
      final String commentId = data['commentId'];
      final DateTime datePublished = data['datePublished']; // ここでエラーが発生!!!
      final String text = data['text'];
      final String uid = data['uid'];
      return Comment(commentId, datePublished, text, uid);
    }).toList();

    this.comments = _comments;

    notifyListeners();
  }
}

するとこの部分でエラーが発生しました。。。

final DateTime datePublished = data['datePublished'];

ちなみにmodelはこんな感じです。

models/comment.dart
class Comment {
  Comment(this.commentId, this.datePublished, this.text, this.uid);
  String commentId;
  DateTime datePublished;
  String text;
  String uid;
}

どうやらFirestoreから取得した段階ではTimeStampなので、Commentモデルで指定されてあるDateTimeに変換してあげないとダメなようです:frowning2:

DateTimeに変換

final DateTime datePublished = data['datePublished'].toDate();

toDateというメソッドがあるようで、これを追加するだけでDateTimeに変換できます!!:v:

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?