🔥

【Firestore】Firestore から取得した Timestamp を DateTime に変換する

2021/05/15に公開

Firestoreのセットアップ

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter

  # Add
  firebase_core: ^1.1.1
  # Add
  cloud_firestore: ^2.1.0

main.dart

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';

void main() async {
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp();
    runApp(MyApp());
}

TimestampからDateTimeへの変換

実装例

import 'package:cloud_firestore/cloud_firestore.dart';

class ApiDataSource {
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  Future<DateTime> fetch() async {
    final document = await _firestore
        .collection('collectionId')
        .doc('documentId')
        .get()
        .catchError((e) => print(e));

    final timestamp = document['createdAt'];
    DateTime createdAt = DateTime.now();
    if (timestamp is Timestamp) {
      createdAt = timestamp.toDate();
    }
    return createdAt;
  }
}

Discussion