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
に変換してあげないとダメなようです
DateTime
に変換
final DateTime datePublished = data['datePublished'].toDate();
toDate
というメソッドがあるようで、これを追加するだけでDateTime
に変換できます!!
参考