lib/photo_list_screen.dart
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:photoapp/photo.dart';
import 'package:photoapp/photo_repository.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> {
// ...
@override
Widget build(BuildContext context) {
final User user = FirebaseAuth.instance.currentUser!;
return Scaffold(
// ...
body: StreamBuilder<List<Photo>>(
// リポジトリ経由でデータを取得する
stream: PhotoRepository(user).getPhotoList(),
builder: (context, snapshot) {
if (snapshot.hasData == false) {
return Center(
child: CircularProgressIndicator(),
);
}
// URL一覧ではなくモデル一覧が取得できる
final List<Photo> photoList = snapshot.data!;
return PageView(
controller: _controller,
onPageChanged: (int index) => _onPageChanged(index),
children: [
//「全ての画像」を表示する部分
PhotoGridView(
// 処理を行う際はモデルを受け渡す
photoList: photoList,
onTap: (photo) => _onTapPhoto(photo, photoList),
),
//「お気に入り登録した画像」を表示する部分
PhotoGridView(
photoList: photoList,
onTap: (photo) => _onTapPhoto(photo, photoList),
),
],
);
},
),
// ...
);
}
// ...
void _onTapPhoto(Photo photo, List<Photo> photoList) {
Navigator.of(context).push(
MaterialPageRoute(
// 処理を行う際はモデルを受け渡す
builder: (_) => PhotoViewScreen(
photo: photo,
photoList: photoList,
),
),
);
}
Future<void> _onAddPhoto() async {
final FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.image,
);
if (file != null) {
// リポジトリ経由でデータを保存する
final User user = FirebaseAuth.instance.currentUser!;
final PhotoRepository repository = PhotoRepository(user);
final File file = File(result.files.single.path!);
await repository.addPhoto(file);
}
}
}
class PhotoGridView extends StatelessWidget {
const PhotoGridView({
Key? key,
required this.photoList,
required this.onTap,
}) : super(key: key);
final List<Photo> photoList;
final Function(Photo photo) onTap;
@override
Widget build(BuildContext context) {
return GridView.count(
// ...
children: photoList.map((Photo photo) {
return Stack(
children: [
SizedBox(
width: double.infinity,
height: double.infinity,
child: InkWell(
onTap: () => onTap(photo),
child: Image.network(
photo.imageURL,
fit: BoxFit.cover,
),
),
),
// ...
],
);
}).toList(),
);
}
}