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:flutter_riverpod/flutter_riverpod.dart';
import 'package:photoapp/photo.dart';
import 'package:photoapp/photo_repository.dart';
import 'package:photoapp/photo_view_screen.dart';
import 'package:photoapp/providers.dart';
import 'package:photoapp/sign_in_screen.dart';
class PhotoListScreen extends StatefulWidget {
@override
_PhotoListScreenState createState() => _PhotoListScreenState();
}
class _PhotoListScreenState extends State<PhotoListScreen> {
late PageController _controller;
@override
void initState() {
super.initState();
_controller = PageController(
// Riverpodを使いデータを受け取る
initialPage: context.read(photoListIndexProvider).state,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
// ...
body: PageView(
controller: _controller,
onPageChanged: (int index) => _onPageChanged(index),
children: [
// 「全ての画像」を表示する部分
Consumer(builder: (context, watch, child) {
// 画像データ一覧を受け取る
final asyncPhotoList = watch(photoListProvider);
return asyncPhotoList.when(
data: (List<Photo> photoList) {
return PhotoGridView(
photoList: photoList,
onTap: (photo) => _onTapPhoto(photo, photoList),
);
},
loading: () {
return Center(
child: CircularProgressIndicator(),
);
},
error: (e, stackTrace) {
return Center(
child: Text(e.toString()),
);
},
);
}),
//「お気に入り登録した画像」を表示する部分
Consumer(builder: (context, watch, child) {
// 画像データ一覧を受け取る
final asyncPhotoList = watch(photoListProvider);
return asyncPhotoList.when(
data: (List<Photo> photoList) {
return PhotoGridView(
photoList: photoList,
onTap: (photo) => _onTapPhoto(photo, photoList),
);
},
loading: () {
return Center(
child: CircularProgressIndicator(),
);
},
error: (e, stackTrace) {
return Center(
child: Text(e.toString()),
);
},
);
}),
],
),
// ...
bottomNavigationBar: Consumer(
builder: (context, watch, child) {
// 現在のページを受け取る
final photoIndex = watch(photoListIndexProvider).state;
return BottomNavigationBar(
// ...
);
},
),
);
}
void _onPageChanged(int index) {
// ページの値を更新する
context.read(photoListIndexProvider).state = index;
}
void _onTapBottomNavigationItem(int index) {
_controller.animateToPage(
index,
duration: Duration(milliseconds: 300),
curve: Curves.easeIn,
);
// ページの値を更新する
context.read(photoListIndexProvider).state = index;
}
void _onTapPhoto(Photo photo, List<Photo> photoList) {
final initialIndex = photoList.indexOf(photo);
Navigator.of(context).push(
MaterialPageRoute(
// ProviderScopeを使いScopedProviderの値を上書きできる
// ここでは、最初に表示する画像の番号を指定
builder: (_) => ProviderScope(
overrides: [
photoViewInitialIndexProvider.overrideWithValue(initialIndex)
],
child: PhotoViewScreen(),
),
),
);
}
// ...
}
// ...