5-4.(p.65)lib/photo_list_screen.dart


lib/photo_list_screen.dart

import 'dart:io';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:file_picker/file_picker.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:photoapp/photo_view_screen.dart';
import 'package:photoapp/sign_in_screen.dart';

class PhotoListScreen extends StatefulWidget {
  @override
  _PhotoListScreenState createState() => _PhotoListScreenState();
}

class _PhotoListScreenState extends State<PhotoListScreen> {

  // ...

  Future<void> _onAddPhoto() async {
    // ...
    if (result != null) {
      // ...
      final TaskSnapshot task = await FirebaseStorage.instance
          .ref()
          .child('users/${user.uid}/photos')
          .child(path)
          .putFile(file);
      
      // アップロードした画像のURLを取得
      final String imageURL = await task.ref.getDownloadURL();
      // アップロードした画像の保存先を取得
      final String imagePath = task.ref.fullPath;
      // データ
      final data = {
        'imageURL': imageURL,
        'imagePath': imagePath,
        'isFavorite': false, // お気に入り登録
        'createdAt': Timestamp.now(), // 現在時刻
      };
      // データをCloud Firestoreに保存
      await FirebaseFirestore.instance
          .collection('users/${user.uid}/photos') // コレクション
          .doc() // ドキュメント(何も指定しない場合は自動的にIDが決まる)
          .set(data); // データ
    }
  }
}

// ...