6-1.(p.73)model / repository


model / repository

class PhotoListScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final User user = FirebaseAuth.instance.currentUser!;

    return Scaffold(
      // モデルとして値を受け取る
      body: StreamBuilder<List<Photo>>(
        // リポジトリから取得処理を行う
        stream: PhotoRepository(user).getPhotoList(),
        builder: (context, snapshot) {
          final List<Photo> photoList = snapshot.data!;

          return GridView.count(
            crossAxisCount: 2,
            children: photoList.map((photo) {
              return Image.network(photo.imageURL);
            }).toList(),
          );
        },
      ),
    );
  }
}

// モデル
class Photo {
  Photo({
    this.id,
    required this.imageURL,
    required this.imagePath,
    required this.isFavorite,
    this.createdAt,
  });

  final String? id;
  final String imageURL;
  final String imagePath;
  final bool isFavorite;
  final DateTime? createdAt;
}

// リポジトリ
class PhotoRepository {
  PhotoRepository(this.user);

  final User user;

  Stream<List<Photo>> getPhotoList() {
    return FirebaseFirestore.instance
        .collection('users/${user.uid}/photos')
        .orderBy('createdAt', descending: true)
        .snapshots()
        .map(_queryToPhotoList);
  }

  List<Photo> _queryToPhotoList(QuerySnapshot query) {
    return query.docs.map((doc) {
      return Photo(
        id: doc.id,
        imageURL: doc.get('imageURL'),
        imagePath: doc.get('imagePath'),
        isFavorite: doc.get('isFavorite'),
        createdAt: (doc.get('createdAt') as Timestamp).toDate(),
      );
    }).toList();
  }
}